I\'m trying to generate an array of random numbers from 0-n then shuffle (but ensure that the keys and values DO NOT match).
For example:
0 => 3
1
What's about combining range(...)
(for generating the original array first), shuffle(...)
(to randomize the array), and array_intersect_assoc(...)
(for checking the result array)?
$numbers = range(0, 4);
do {
shuffle($numbers); // print_r($numbers);
$matchingKeyValuePairs = array_intersect_assoc(array_keys($numbers), array_values($numbers)); // print_r($matchingKeyValuePairs);
} while (! empty($matchingKeyValuePairs));
This solution might bring some performance issues for big numbers of elements. But it can be extended by a logic for dealing with the $matchingKeyValuePairs
. So while now the logic is like "IF there are matchingKeyValuePairs
THEN try it again", a much more efficient logic migth be "IF there are matchingKeyValuePairs
THEN cut the matchingKeyValuePairs
from the array, randomize this sub-array (multiple times, if needed), and merge it back".