duankanjian4642
2017-03-16 14:41
浏览 81
已采纳

如何从一个范围生成3个非重复随机数? [重复]

This question already has an answer here:

Using PHP, how can I select 3 numbers from a numbers range, that don't repeat theirselves?

For example from a range 1 - 100, an answer may be 5, 32, 12, but not 5, 5, 93

Thank you

</div>

图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 这里有一个答案:

  • 生成无重复的随机数 2 answers

    使用PHP,如何从数字范围中选择3个不重复的数字?

    例如,范围为1 - 100,答案可能是5,32,12,但不是5,5,93

    谢谢

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doudun3910 2017-03-16 14:50
    已采纳

    Create array of numbers from 1 to 100:

    $numbers = range(1, 100);
    

    Shuffle all numbers:

    shuffle($numbers);
    

    Retrieve only 3 of them:

    $randomNumbers = array_slice($numbers, 0, 3);
    
    已采纳该答案
    打赏 评论
  • dstew32424 2017-03-16 14:47

    Try this:

    $numbers = [];
    $min = 1;
    $max = 3;
    
    for($i=0; $i<3; $i++){
        $rnd = rand($min, $max);
        while(in_array($rnd, $numbers)){ // while generated random number is already in the numbers array
            $rnd = rand($min, $max); // generate a new random number
        } // loop ends when newly generated random number is not in the array already
        array_push($numbers, $rnd); // push the new random number into the array
    }
    

    It will generate 3 different numbers between 1 and 3, and save them into the $numbers array.

    打赏 评论

相关推荐 更多相似问题