To randomise an array in PHP use the shuffle() function like this.
There are two limitations to this function. The first is that it completely removes any key association that you may have set up. So the following array.
$array = array('one'=>1,'two'=>2);
Would be turned into the following after using shuffle().
Array ( [0] => 2 [1] => 1 )
A way around this is to use the following function, this uses the PHP function array_rand() to extract the all of the keys in the array in a random order before ensuring that the key associations are in place.
function shuffle_me($shuffle_me){ foreach($randomized_keys as $current_key) { $shuffled_me[$current_key] = $shuffle_me[$current_key]; } return $shuffled_me; }
The second limitation to the shuffle() function is the degree of randomness that is created. In order to give a rough estimate of how random a randomising function is you can use the following code.
$rangeStart = 1; $rangeEnd = 2; $loops = 100000; for($i=0;$i<=$loops;$i++){ }; echo '<p>Start: '.$start.' End: '.$end.' Difference: '.($start-$end).'</p>';
This code runs a loop 100,000 times, each time it creates a small array containing the values 1 and 2, randomises it and then stores the result as a string of numbers in another array. After the loop the PHP function array_count_values() is used to count the number of times that each value has been created and then looks to see the difference between the the lowest occurring value and the highest occurring value. The greater the number the more random the randomising function is. This shouldn't be used as the absolute truth because there are more factors at work with randomising arrays, but it gives a nice approximation.
To get a good level of randomness with an array randomising function you should use the Fisher-Yates shuffle. Here is an example of a function that uses this algorithm.
function array_shuffle($array){ // shuffle using Fisher-Yates while(--$i){ if($i != $j){ // swap items $tmp = $array[$j]; $array[$j] = $array[$i]; $array[$i] = $tmp; } } return $array; }
Using the previously mentioned random testing code it was found that the native PHP shuffle() function gave an average difference of 27, whereas the Fisher-Yates shuffle gave an average difference of 273.
So if randomness is very important to you then you probably shouldn't use the shuffle() function.