Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何从一个范围生成3个不重复的随机数?_Php - Fatal编程技术网

Php 如何从一个范围生成3个不重复的随机数?

Php 如何从一个范围生成3个不重复的随机数?,php,Php,使用PHP,如何从一个数字范围中选择3个不重复自身的数字 例如,从1到100,答案可能是5、32、12,但不是5、5、93 谢谢试试这个: $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 n

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

例如,从1到100,答案可能是5、32、12,但不是5、5、93

谢谢

试试这个:

$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
}
$numbers=[];
$min=1;
$max=3;

对于($i=0;$i创建从1到100的数字数组:

$numbers = range(1, 100);
洗牌所有数字:

shuffle($numbers);
仅检索其中的3个:

$randomNumbers = array_slice($numbers, 0, 3);

你自己试过什么吗?谷歌是你的朋友。只要查一下怎么做,然后做x次,直到你得到3个数字。最简单的方法是使用循环检查最后生成的数字,如果与最后一个数字匹配,则忽略新的:)范围,洗牌切片。@Abracadver干杯,你刚刚让我想到蛋糕。