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

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

Comments

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 Comment

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.
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
)

1 Comment

@gordon falvey: it is clearly tested.
-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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.