PHP's shuffle()
function destroys the array keys, so I decided to write a shuffle function that doesn't do that and instead rearranges key-value associations. As I would be using the function in place of shuffle()
most of the time, I'd like it to be as fast and memory efficient (if a time-space tradeoff is needed, I think I would prioritise time) as possible:
<?
function swap(&$a, &$b)
{
$tmp = $a;
$a = $b;
$b = $tmp;
}
function shuffleX(&$arr) #Shuffles the key-value associations in an array.
{
$keys = array_keys($arr); #extract the keys from the array.
$length = count($keys);
$i = 0; #Index.
while ($i < $length-1)
{
$target = rand(($i+1), $length-1); #This ensures that no value ends up mapped to the same key.
swap($arr[$keys[$i]], $arr[$keys[$target]]); #Swap each element of the array with another.
$i++;
}
}
?>