PHP: How to Scramble an Array CodeUnit 16 NOV 2011

PHP comes packaged with an awesome little function that makes scrambling an array, i.e. randomly rearranging its contents, a doddle. Aptly named shuffle, the shuffle() function randomizes the order of elements in an array.

As an input array, you simply need to pass it the array to be shuffled, with the function returning either true or false depending on the outcome. The array is passed in by reference, meaning that the original array is shuffled. Note also that existing keys are removed and new keys are assigned, making it useless for associative arrays where the key/value pairs are actually important.

Nevertheless, still a pretty useful function in my opinion. To use:

$numbers = array(1,2,3,4,5);
shuffle($numbers);
print_r($numbers);

Nifty.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.