Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP shuffle() function

Reference for PHP shuffle(): randomize the order of an array in place, what happens to keys, how to shuffle a copy or an associative array, and security limits.

shuffle() rearranges the elements of an array into random order, in place. The array is passed by reference, so the function changes your variable and returns only true. Do not assign the result back to the array, or you will replace it with true.

All keys are discarded and the result is a list with keys 0, 1, 2, .... To shuffle an associative array while keeping its keys, shuffle the keys and rebuild the array.

PHP
<?php
$cards = ["A", "K", "Q"];
shuffle($cards);
echo count($cards);   // 3, in random order

Try it

PHP Shuffling a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Keeping the keys of an associative array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
shuffle(array &$array): true
Name Description
$array The array to shuffle. Passed by reference and modified.

Return value: always true (PHP 8.2 and later; older versions declared bool).

Usage notes

  • In place: the original order is lost. Copy the array first if you still need it (arrays are copied on assignment).
  • Keys are lost: string keys are removed and numeric keys renumbered. Use the key-shuffling pattern above for associative arrays.
  • Not for secrets: shuffle() uses the Mersenne Twister generator, which can be seeded with mt_srand(). For cryptographic shuffles, use Random\Randomizer::shuffleArray() with a secure engine (PHP 8.2+).
  • Fair: each permutation is equally likely; do not implement your own shuffle with usort() and rand(), which is biased.
  • Picking a few random items is cheaper with array_rand() than shuffling a big array.
  • Strings: the sibling str_shuffle() shuffles the characters of a string.