How do you shuffle a PHP array while still knowing the original index?
I have a simple array in PHP (e.g. ["a", "b", "c", [5, 10]]
).
The shuffle()
function allows you to shuffle the elements.
However I still wish know what the original index was. How can I do this?
See shuffle doc 2nd example:
<?php
function shuffle_assoc(&$array) {
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $array[$key];
}
$array = $new;
return true;
}
Do you mean shuffle the elements and keep them with their keys, so if you foreach
over them they come out in a shuffled order? That's possible by reshaping the array into a list of [key, value]
pairs:
$pairs = array_map(null, array_keys($array), array_values($array));
So ["a", "b", "c", [5, 10]]
becomes [[0, "a"], [1, "b"], [2, "c"], [3, [5, 10]]
.
Then, shuffle the pairs:
shuffle($pairs);
Which might end up something like this (random each time obviously):
[[2, "c"], [1, "b"], [3, [5, 10]], [0, "a"]]
Finally, re-shape it into a normal array again:
$shuffled = array_combine(array_column($pairs, 0), array_column($pairs, 1));
End result looks something like this:
[2 => "c", 1 => "b", 3 => [5, 10], 0 => "a"]
Is that what you want?
This is just one way to do it, though. What Gerard suggested is probably more efficient.