Randomize a List in PHP
When the input array is an associative array, then the shuffle() function will randomize the order of elements as well as assigns new keys to the elements starting from zero (0).
<?php
// input array contain some elements which
// need to be shuffled.
$a = array
(
"a"=>"Ram",
"b"=>"Shita",
"c"=>"Geeta",
"d"=>"geeksforgeeks"
);
shuffle($a);
print_r($a);
?>
Output
Array
(
[0] => geeksforgeeks
[1] => Shita
[2] => Ram
[3] => Geeta
)
(
[0] => geeksforgeeks
[1] => Shita
[2] => Ram
[3] => Geeta
)
When the input array is not associative then the shuffle() function will randomize the order and convert the array to an associative array with keys starting from zero (0).
<?php
// input array contain some elements
// which need to be shuffled.
$a = array
(
"ram",
"geeta",
"blue",
"red",
"shyam"
);
shuffle($a);
print_r($a);
?>
Output
Array
(
[0] => red
[1] => geeta
[2] => ram
[3] => shyam
[4] => blue
)
(
[0] => red
[1] => geeta
[2] => ram
[3] => shyam
[4] => blue
)