PHP Array Key Value Shuffle

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.

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.

To test if that works we can just use this.

And we get this.

Nice! That was exactly what I needed.