Last Updated:

PHP: Random number generator

Periodically there is a need to generate random numbers from any developer. There's nothing simpler than the built-in rand(0.100) function, which works fine. However, if you complicate the task...

There is a "box" with numbered chips, for example from 0 to 100. And you extract them from it, naturally their number decreases. It is required to make an array for the number of chips in the box specified in advance.

Solution algorithm:

  • in the loop we generate a number and add it to the array
  • remove duplicates of the array
  • check the number of unique elements of the array, if they are less than the specified number of "chips in the box" repeat the generation
  • overwrite the keys from 0 to a specified number

Generating a random number in PHP: