In this article, we are going to see how to generate a random number using a set of predefined PHP functions. There are 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 sending 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 seed should be changed randomly. If we pass the same seed every time, then the same random number will be created for all attempts.
After PHP version 4, seeding is optional. Without a seeding, PHP rand() and mt_rand() will automatically get such a random integer for creating random numbers.
The following PHP code will print random numbers to the browser-based on the functions used. The first two lines are used for the 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.
<?php srand(time()); mt_srand(time()); echo rand() . "<br>"; echo mt_rand() . "<br>"; echo rand(20, 1000) . "<br>"; echo mt_rand(1, 10) . "<br>"; ?>