Generate array of random unique numbers in PHP

前端 未结 7 890
再見小時候
再見小時候 2020-12-11 15:09

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         


        
相关标签:
7条回答
  • 2020-12-11 15:42

    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".

    0 讨论(0)
提交回复
热议问题