Shuffle an associative array with PHP

Josh Sherman
1 min read
Software Development PHP

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!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles