How to shuffle an array
Short answer
shuffle() shuffles the array in place:
<?php
$cards = ['A', 'K', 'Q', 'J'];
shuffle($cards);
echo implode(' ', $cards);Keeping the keys
shuffle() loses the keys. To keep them, shuffle the keys and rebuild the array:
<?php
$prices = ['tea' => 250, 'coffee' => 400, 'juice' => 180];
$keys = array_keys($prices);
shuffle($keys);
$shuffled = [];
foreach ($keys as $key) {
$shuffled[$key] = $prices[$key];
}
echo json_encode($shuffled);Several random elements
array_rand() returns random keys:
<?php
$winners = ['Anna', 'Oleg', 'Ivan', 'Maria', 'Petr'];
foreach (array_rand($winners, 2) as $key) {
echo $winners[$key], ' ';
}Functions used in this recipe
- shuffle — Shuffles the elements of an array into a random order.
- array_rand — Returns a random key of an array.
- random_int — Returns a random integer from a range.