shuffle

Randomizes the order of an array's elements in place and reindexes it from zero.

Signature
shuffle(array &$array): true
  • Added in PHP 4.0

Parameters

ParameterTypeDescription
$arrayarrayThe array to shuffle. Passed by reference; existing keys are discarded and replaced with 0-based integers.

Return value

trueAlways returns true. The array is shuffled in place through the reference.

Errors

Nothing. A non-array argument raises a TypeError from the parameter type.

Changelog

  • PHP 8.2The return type is true now; previously it was bool.
  • PHP 7.1The internal randomization algorithm now uses the Mt19937 (Mersenne Twister) engine instead of the libc rand function.

shuffle rearranges an array into a random order, assigns new keys starting at 0, and resets the internal pointer. It draws from the global Mt19937 generator, which it shares with mt_rand and array_rand.

When to reach for it

Randomising quiz questions or answer options, picking a rotating banner, ordering a playlist, dealing a deck of cards, or randomising which of several equivalent servers you try first. When you only need a few random items rather than the whole array reordered, array_rand is cheaper — it picks keys without moving anything.

What trips people up

Keys are destroyed. Shuffling ['id7' => 'a', 'id9' => 'b'] leaves you with [0 => …, 1 => …] and no way back. If the keys matter, shuffle the keys instead: $keys = array_keys($arr); shuffle($keys); then read the original array through them.

It is not cryptographically secure. The global Mersenne Twister is predictable from enough observed output, so never use shuffle for tokens, password characters, lottery draws or anything an attacker benefits from guessing. Use new Random\Randomizer(new Random\Engine\Secure()) and its shuffleArray method for those. Seeding mt_srand before shuffling gives reproducible output for tests, but that same reproducibility is exactly what makes it unsafe for secrets.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Randomise quiz question order and the answer options within each question.
  • Rotate the display order of homepage banners or testimonials on each page load.
  • Deal a shuffled deck in a card game by shuffling range(1, 52).

Frequently asked questions

Does shuffle preserve array keys?

No. It discards all keys and renumbers the array from 0. Shuffle array_keys($arr) and look values up through the shuffled keys if you need the keys kept.

Is shuffle random enough for passwords or tokens?

No. It uses the global Mersenne Twister, which is predictable given enough output. Use Random\Randomizer with Random\Engine\Secure, or random_int, for anything security-sensitive.

How do I get the same shuffle every time in a test?

Call mt_srand() with a fixed seed before shuffle(); the global Mt19937 engine will then produce the same sequence on each run.

More examples

Shuffling without losing the keys

Shuffling the key list instead of the array gives a random presentation order while $questions itself is untouched — the last line shows its keys are still q1, q2, q3.

Example · php
<?php
mt_srand(7);
$questions = ['q1' => 'Capital of Peru?', 'q2' => 'Largest ocean?', 'q3' => '2 + 2?'];

$keys = array_keys($questions);
shuffle($keys);

foreach ($keys as $k) {
    echo $k, ': ', $questions[$k], "\n";
}
echo json_encode(array_keys($questions)), "\n";

shuffle versus array_rand

shuffle reorders the whole array so you can take any slice from the front. array_rand returns keys only, in ascending key order rather than random order, and does not modify the source — cheaper when you just need a couple of picks.

Example · php
<?php
mt_srand(1);
$pool = ['a', 'b', 'c', 'd', 'e'];

$copy = $pool;
shuffle($copy);
echo 'shuffled: ', implode(',', $copy), "\n";
echo 'first 2:  ', implode(',', array_slice($copy, 0, 2)), "\n";

$picks = array_rand($pool, 2);
echo 'array_rand keys: ', implode(',', $picks), "\n";

Discussion

  • Be the first to comment on this lesson.