In this article, we are going to see how to generate a random number using a set of predefined PHP functions. There is two prime functions to deal with random number generation. These are,
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 sent as a seed should be changed randomly. If we pass same seed every time, then the 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.
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 a 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.