Fisher–Yates Shuffle
Fisher–Yates shuffle, also known as Knuth shuffle, is an algorithm for generating a random permutation of a finite set—in plain terms, the algorithm shuffles the set. The algorithm effectively puts all the elements into a hat; it continually determines the next element by randomly drawing an element from the hat until no elements remain.
function FisherYatesShuffle($data, $count)
{
$retVal = array();
$ind = array();
$index = 0;
for ($i = 0; $i < $count; ++$i)
$ind[$i] = 0;
for ($i = 0; $i < $count; ++$i)
{
do
{
$index = rand() % $count;
} while ($ind[$index] != 0);
$ind[$index] = 1;
$retVal[$i] = $data[$index];
}
return $retVal;
}
Example
$data = array(486, 87, 522, 111, 894, 371, 1, 39);
$retVal = FisherYatesShuffle($data, 8);
Output
retVal: { 87, 1, 39, 894, 371, 522, 111, 486 }