0

I want to generate an array with random numbers. I don't want the same value to appear twice in the array. I want all five values to be unique. How would I do this?

$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);
scrowler
  • 24,273
  • 9
  • 60
  • 92

4 Answers4

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

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



}
var_dump($rand);
Chris
  • 3,405
  • 4
  • 29
  • 34
  • 1
    this won't always work, as the else statement is only run once. therefore if else statement generates the same number, you're still stuck with duplicates. – skrilled Feb 13 '14 at 19:14
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);
skrilled
  • 5,350
  • 2
  • 26
  • 48
0

Try this:

$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);

Demo: https://eval.in/101433

demo OUTPUT:

Array
(
    [0] => 2
    [1] => 1
    [2] => 4
    [3] => 5
    [4] => 3
)
Awlad Liton
  • 9,366
  • 2
  • 27
  • 53
-1

I have this idea... there should be better ideas, but I think this one:

$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);
dapaez
  • 1
  • 2