Skip to content

Core\Random::shuffle

Core\Random::shuffle(array<T> $a): array<T>Core\Random::shuffle(
    array<T> $a,
): array<T>

Puts every value of an array in a random order, for example to shuffle a deck of cards or to show answers in a different order each time.

Core\Random::shuffle returns a new list with all the values of the array. Every possible order has the same chance. The keys of the new list start again at 0, so the old keys are not kept. The array you pass in does not change. An empty array gives an empty list. The order comes from a cryptographic random generator, so nobody can predict it.

Good to know: when you need only some of the values, use Core\Random::sample.

Parameters

  • $aarray<T>The array to reorder.

Return value

Returns array<T>. A new list of all the values, with the keys 0, 1, …. The keys of $a are not kept, and $a is unchanged.

Examples

Shuffle a deck

<?nvs
// Shows how to shuffle a small deck of cards.
array<string> $deck = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
// `Core\Random::shuffle` returns a new list with the same cards in a random order.
array<string> $shuffled = Core\Random::shuffle($deck);
// The order changes on every run. The cards stay the same, so this prints 13 and `yes`.
echo Core\Arr::count($shuffled), "\n";
echo Core\Json::encode(Core\Arr::sort($shuffled)) == Core\Json::encode(Core\Arr::sort($deck)) ? 'yes' : 'no', "\n";
// The first deck does not change. This prints `A`.
echo $deck[0], "\n";
Output
13
yes
A

Keys are not kept

<?nvs
// Shows that a shuffled array gets new keys, and what happens with an empty array.
array<int> $stock = ['apples' => 4, 'pears' => 4, 'plums' => 4];
// The result is a list, so its keys are 0, 1 and 2. This prints ["0","1","2"].
array<int> $shuffled = Core\Random::shuffle($stock);
echo Core\Json::encode(Core\Arr::keys($shuffled)), "\n";
// Every value is 4, so the result looks the same in any order. This prints [4,4,4].
echo Core\Json::encode($shuffled), "\n";
// An empty array gives an empty list. This prints [].
array<int> $empty = [];
echo Core\Json::encode(Core\Random::shuffle($empty)), "\n";
Output
["0","1","2"]
[4,4,4]
[]

Answers in a new order

<?nvs
// Shows the answers of a quiz question in a new order for each student. Then nobody
// can copy the letter of the right answer from a neighbor.
array<string> $answers = ['Paris', 'Rome', 'Madrid', 'Berlin'];
string $correct = 'Paris';
// Each student gets the answers in a random order, marked A to D.
array<string> $letters = ['A', 'B', 'C', 'D'];
array<string> $shown = Core\Random::shuffle($answers);
// The letter of the right answer changes on every run. It is always one of A to D,
// so this prints `yes`.
string $letter = '';
int $i = 0;
foreach ($shown as string $answer) {
if ($answer == $correct) {
$letter = $letters[$i];
}
$i = $i + 1;
}
echo Core\Arr::contains($letters, $letter) ? 'yes' : 'no', "\n";
Output
yes