PHP Random Number Generator

In this article we are going to see about how to generate random number using set of predefined PHP functions. There are two prime function to deal with random number generation. These are,

  • rand()
  • mt_rand()

rand() vs mt_rand()

  • These two functions might have two optional arguments for specifying min and max limit for generating random number.
  • If the min, max values are not specified, then the limits will be taken automatically, that is, 0 and the value returned by the getrandmax() or mt_getrandmax().
  • The value returned by getrandmax() function is some what limited depends on the platform we are working. In such cases, mt_getrandmax() is used to pick maximum limit for mt_rand() function.
  • mt_rand() is comparatively quicker than rand() function.
  • Seed for the random number generators, rand() and mt_rand() can be provided by srand() and mt_srand() functions respectively

php_random_number_generator

Seeding PHP Random Number generator

PHP has set of functions like srand() and mt_srand() to seed random number generators. Seeding is nothing but to send an integer as an argument of srand() or mt_srand(). Since the random numbers are created based on this integer, we need to call srand() or mt_srand() before calling rand() and mt_rand().

Importantly, the number to be send as a seed should be changed randomly. If we pass same seed every time, then same random number will be created for all attempts.

After PHP version 4, seeding is optional. Without seeding, PHP rand() and mt_rand() will automatically get such random integer for creating random numbers.

Example: PHP Random Number Generator

The following PHP code will print random numbers to the browser based on the functions used. First two lines are used for seeding process. Random numbers will also be generated, without these two lines. The time() function is used to create unique number for seeding at the time of execution.

srand(time());
mt_srand(time());
echo rand() . "<br>";
echo mt_rand() . "<br>";
echo rand(20,1000) . "<br>";
echo mt_rand(1,10) . "<br>";

This PHP code tutorial was published on May 14, 2013.

↑ Back to Top