PHP Unique Random Numbers

前端 未结 6 1689
天涯浪人
天涯浪人 2021-01-14 21:16

What would be a good way to generate 7 unique random numbers between 1 and 10. I can\'t have any duplicates. I could write a chunk of PHP to do this (using rand() and pushin

6条回答
  •  無奈伤痛
    2021-01-14 21:53

    The "shuffle" method has a MAJOR FALW. When the numbers are big, shuffle 3 billion indexs will instantly CAUSE 500 error. Here comes a best solution for really big numbers.

    function getRandomNumbers($min, $max, $total) {
        $temp_arr = array();
        while(sizeof($temp_arr) < $total) $temp_arr[rand($min, $max)] = true;
        return $temp_arr;
    }
    

    Say I want to get 10 unique random numbers from 1 billion to 4 billion.

    $random_numbers = getRandomNumbers(1000000000,4000000000,10);
    

    PS: Execution time: 0.027 microseconds

提交回复
热议问题