PHP makes it really easy to randomize the order of an array with the shuffle() function. If you’ve ever used this function on an associative array you know that the array will be randomized, but the keys will be dropped. It takes a bit more work, but you can randomize an associative array by shuffling the array keys and then reassembling the array.

$sorted_array = array(
	'a' => 'aaaaa',
	'b' => 'bbbbb',
	'c' => 'ccccc',
	'd' => 'ddddd',
	'e' => 'eeeee',
	'f' => 'fffff',
	'g' => 'ggggg',

$shuffled_array = array();

$keys = array_keys($sorted_array);

foreach ($keys as $key)
	$shuffled_array[$key] = $sorted_array[$key];

print_r($shuffled_array); // so we can see it shuffled up :)

As mentioned, it’s a bit more work, but gets the job done. I have a few alternative methods floating around my head, but this method has always proved reliable. If you sort associative arrays differently, I’d love to hear from you!

Did you enjoy this post?

Cool if I slip into your inbox with more?
Full posts, 1-2 times per week: