0

I want to create 8 random integers, that are unique and in the range between 0 and 99.

Is there a neater solution, than the one that I thought of?

<?php


do {

  $rnd1 = rand(0,99);
  $rnd2 = rand(0,99);
  $rnd3 = rand(0,99);
  $rnd4 = rand(0,99);
  $rnd5 = rand(0,99);
  $rnd6 = rand(0,99);

} while (($rnd1 == $rnd2) || 
         ($rnd1 == $rnd3) || 
         ($rnd1 == $rnd4) || 
         ($rnd1 == $rnd5) || 
         ($rnd1 == $rnd6) || 
         ($rnd2 == $rnd3) || 
         ($rnd2 == $rnd4) || 
         ($rnd2 == $rnd5) || 
         ($rnd2 == $rnd6) || 
         ($rnd3 == $rnd4) || 
         ($rnd3 == $rnd5) || 
         ($rnd3 == $rnd6) || 
         ($rnd4 == $rnd5) || 
         ($rnd4 == $rnd6) || 
         ($rnd5 == $rnd6)    );


?>
2
  • $range = range(0, 99); shuffle($range); $rand_ints = array_slice($range, 0, 8); Commented Oct 6, 2015 at 10:34
  • @Lin you are not permitted to deface your question. Commented Mar 14 at 11:05

3 Answers 3

2

Try the code below.
It will create an array containing 8 random values between 0 and 99 while checking if they have been added already to ensure they are unique across.

$numbers = array();
while ( count($numbers) <= 8 ) {
    $x = mt_rand(0,99); 
    if ( !in_array($x,$numbers) ) {
        $numbers[] = $x;
    }
}
print_r($numbers);

Also see these two Q&A's about using mt_rand vs. rand
Difference between mt_rand() and rand()
What's the disadvantage of mt_rand?

Sign up to request clarification or add additional context in comments.

1 Comment

Also note that we have random_int
1

This is an optimized version that relies on the array indexes. The complexity of this solution is linear rather than n2 as in @AlexAndrei's answer. It relies on using array indexes as the guarantee there are no duplicates so there is no need to add the overhead of in_array.

$random_numbers = [];

do {
  $rand = rand(0, 99);
  $random_numbers[$rand] = $rand;
} while( count($random_numbers) < 9 );

$random_numbers = array_values($random_numbers); // This strips the keys

print_r($random_numbers);

If you are using a foreach you can even drop the array_values call which would also increase the speed of your code, but the numbers in the array will be in the form: [ a => a, b => b, ... ]

1 Comment

Though you can use mt_rand() instead of rand() which should theoretically speed up the avarage generation process because of mt_rand()'s higher entropy.
-1
$rnds = [];

do {
  $newRnd = rand(0, 99);
  $rnds[] = $newRnd;
} while(in_array($newRnd, $rnds) && count($rnds) < 9);

print_r($rnds);

1 Comment

If there is a duplicate, this would only do another itteration of the (do while) loop, not actually remove/overwrite it. Stub the rand with 5 and you will see that I am correct.