Shuffle an associative array with 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
shuffle($keys

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!

Josh Sherman - The Man, The Myth, The Avatar

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.


If you found this article helpful, please consider buying me a coffee.