PHP Unique Random Numbers

前端 未结 6 1644
天涯浪人
天涯浪人 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:40

    Populate an array with ten elements (the numbers one through ten), shuffle the array, and remove the first (or last) three elements.

    0 讨论(0)
  • 2021-01-14 21:43

    Simple one-liner:

    print_r(array_rand(array_fill(1, 10, true), 7));
    
    0 讨论(0)
  • 2021-01-14 21:43

    Whole numbers? Well, if you want 7 out of 10 then you more efficiently DON'T want 3 out of 10.

    Feel free to use any of the other responses but instead of creating 7 numbers start with 10 and eliminate 3. That will tend to speed things up by more than double.

    0 讨论(0)
  • 2021-01-14 21:47
    • Create an array from 1 to 10 (range).
    • Put it in random order (shuffle).
    • Select 7 items from the array (array_slice)
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-14 22:02

    Check out the comments in the php manual, there are several solutions for this.

    An easy one is this one:

    $min = 1;
    $max = 10;
    $total = 7;
    $rand = array();
    while (count($rand) < $total ) {
        $r = mt_rand($min,$max);
        if (!in_array($r,$rand)) $rand[] = $r;
    }
    
    0 讨论(0)
提交回复
热议问题