Generating Random Numbers In PHP |
| Written by phpecho.com | |||
In this short tutorial we look at how random numbers are generated in PHP. As with any technology system, random number generators in effect generate only pseudo-random numbers. This is because computer systems and programming interpreters, as we know them today, are deterministic, i.e., given an input, the output is constant. So, the concept of seeding is used. Seeding a random number is the process of providing an input to a mathematical function which generates a series of numbers. The first of those numbers is the first random number. The second random number is derived by passing the first random number as the input to the same mathematical function. The two most common functions used in PHP to generate random numbers are rand() and mt_rand(). The mt_rand() function is considered to return more random numbers than the rand() function. The usage is similar for both. In fact there are two variances of usage of these functions. One is the one without any arguments and the other with two arguments. When you use rand() or mt_rand() with no arguments, then a random number between 0 and the maximum random number possible is generated. The maximum random number possible can be obtained by using the function getrandmax() function. Consider the example below: <?php
echo ("Example to show generation of random numbers<br>");
echo ("Start - seeding the generator<br>");
srand((double)microtime * 1000000);
echo ("Maximum random number is - ".getrandmax()."<br>");
echo ("End - seeding complete<br>");
echo ("First random number - ".rand().'<br>');
echo ("Second random number - ".rand().'<br>');
echo ("Third random number - ".rand().'<br>');
echo ("Fourth random number - ".rand(10, 45).'<br>');
echo ("Fifth random number - ".rand(23, 50).'<br>');
?>
The output when the program is executed is something like this - Example to show generation of random numbers Obviously you will not get the same results as above since these are random numbers generated. The third line in the code is used to seed the generator with a start value. In this case the current time is used for it. The advantage with this is every time this is executed, a new seed will get generated. The first three random numbers are generated with no arguments while the fourth and fifth are generated with two arguments. When two arguments are used, then the generated random number will be between the given arguments. The syntax for mt_rand is exactly similar to that of rand but the results are considered more random.
|