生成具有唯一随机数的数组

时间:2014-02-13 19:08:24

标签: php arrays

我想生成一个随机数的数组。我不希望相同的值在数组中出现两次。我希望所有五个值都是唯一的。我该怎么做?

$rand1 = rand(1, 50);
$rand2 = rand(1, 50);
$rand3 = rand(1, 50);
$rand4 = rand(1, 50);
$rand5 = rand(1, 50);

$input = array($rand1,$rand2,$rand3,$rand4,$rand5);
print_r($input);

4 个答案:

答案 0 :(得分:0)

$x=0;
$rand=array();
while ($x<5) {
    $r=rand(1, 50);
    if(in_array($r, $rand)){

    }else{
    $rand[] = $r;
    $x++;
    }



}
var_dump($rand);

答案 1 :(得分:0)

$total = 10; // total random numbers to create

$randoms = array();

for($i=0;$i<=$total;$i++)
{
  $randomNumber = rand(1,50);
  while(in_array($randomNumber,$randoms)) {
    $randomNumber = rand(1,50);
  }
  $randoms[] = $randomNumber;
}

var_dump($randoms);

答案 2 :(得分:0)

试试这个:

$a = array();
for($i=0;$i<5;$i++){
 $rand1=rand(1, 5);
  while(in_array( $rand1,$a)){
   $rand1=rand(1, 5);
  }
  $a[$i] = $rand1;

}
print_r($a);

演示:https://eval.in/101433

demo OUTPUT:

Array
(
    [0] => 2
    [1] => 1
    [2] => 4
    [3] => 5
    [4] => 3
)

答案 3 :(得分:-1)

我有这个想法......应该有更好的想法,但我认为这个:

$rand1 = rand(1, 50);
do{
    $rand2 = rand(1, 50);
}while($rand2==$rand1); 

do{
    $rand3 = rand(1, 50);
}while($rand3==$rand2 || $rand3==$rand1); 


do{
    $rand4 = rand(1, 50);
}while($rand4==$rand3 || $rand4==$rand2 || $rand4==$rand1);

 do{
    $rand5 = rand(1, 50);
}while($rand5==$rand4 || $rand5==$rand3 || $rand5==$rand2 || $rand5==$rand1);

$input = array($rand1,$rand2,$rand3,$rand4,$rand5); print_r($input);