List of unique random numbers in PHP

When we are working with generated random numbers, it is possible that one of the numbers will be repeated, the more limited the set of random numbers we work with is. We already saw how generate a list of random numbers in PHP, now we are going to generate a list of unique random numbers in PHP.

The first thing will be to create the array that will contain the list:

$values ​​= array();

In this case we cannot use a finite control loop like a for, since, a priori, we cannot know how many times we need to call the function rand. That is why we will define a control variable that helps us control the list of unique random numbers.

$x = 0;

We will increase this variable every time we find a unique random number.

Now we set up the loop that will control said variable. In the loop $num represents the maximum number of unique random numbers we want to generate.

while ($x<$num) {...}

The next thing will be to generate the random number with rand. For example, from 1 to 100.

$random_num = rand(1,100);

The next thing will be to check whether or not said random number already exists. To check this we look inside the array with the function in_array. If the new random number is not found in the array, it is when we insert it into the array with array_push and we increment our control variable.

The code would look like this:

while ($x<$num) {
  $random_num = rand(1,$max);
  if (!in_array($random_num,$values)) {
    array_push($values,$random_num);
    $x++;
  }
}

We will only have to use the list of unique random numbers in PHP. What could you use it for?

Leave a Comment