Recently I had need to shuffle an array, but keep the associative keys. Here’s the simple function to do that.
Let’s say that we have six tickets to the movies, but we want to randomize who gets what ticket. My use case was more complicated, but you get the idea.
So we have our starting assignment, just in alphabetical order.
11 12 13 14 15 16 17 18 |
$seats = [ "G14" => "Alice", "G15" => "Bob", "G16" => "Charlie", "G17" => "Diane", "G18" => "Ellen", "G19" => "Felix", ]; |
I had wanted to use array_shuffle()
but that destroys the keys. We wouldn’t know what the seats were anymore. So here’s a small bit of code that will mix up the seat assignments.
3 4 5 6 7 8 9 |
function arrayValueShuffle(array $array) { $keys = array_keys($array); shuffle($array); return array_combine($keys, $array); } |
To test if that works we can just use this.
20 |
var_export(arrayValueShuffle($seats)); |
And we get this.
1 2 3 4 5 6 7 8 |
array ( 'G14' => 'Ellen', 'G15' => 'Diane', 'G16' => 'Alice', 'G17' => 'Bob', 'G18' => 'Charlie', 'G19' => 'Felix', ) |
Nice! That was exactly what I needed.