There are many methods to generate random numbers in php: rand () is actually a function that can also be generated using mt_rand (). I will not talk about the difference here.
The rand () function returns a random integer.
Syntax
Rand (min, max) parameter description
Min, max (optional. Specifies the range of random numbers.
If no optional parameter is providedMinAndMax, Rand () returns a pseudo-random integer between 0 and RAND_MAX. For example, if you want a random number between 5 and 15 (including 5 and 15), use rand (5, 15 ).
To generate a random number in PHP, follow these three steps:
| The Code is as follows: |
Copy code |
// Step 1: Initialize the seed
$ Seedarray = microtime ();
$ Seedstr = split ("", $ seedarray, 5 );
$ Seed = $ seedstr [0] * 1000000;
|
// Step 2: Use the seed to initialize the random number generator
| The Code is as follows: |
Copy code |
Srand ($ seed );
|
// Step 3: generate a random number within the specified range
| The Code is as follows: |
Copy code |
| $ Random = rand (0,1000 ); |
The preceding two steps do not need to be modified, that is, the last step. (1000) indicates that a random number (including 0) is generated between 0 and ), this range can be changed to the one you need.
There is also a simpler code for generating random numbers:
| The Code is as follows: |
Copy code |
|
Srand (double) microtime () * 1000000 );
$ Random = rand (0,1000 ); |
Microtime () returns two values: the current number of milliseconds and the timestamp. Because we only need to extract random numbers, we can use the number of milliseconds. (Double) microtime () indicates that only the current millisecond value is returned. Microtime () is the number of milliseconds in seconds. Therefore, the values are decimal places and multiplied by 1000000 to convert them into integers. The second code indicates that a random number is generated between 0 and 1000.
Tips and comments
Note: In some platforms (such as Windows), RAND_MAX only has 32768. If the required range is greater than 32768, specify the min and max parameters to generate a number greater than RAND_MAX, or use mt_rand () instead.
Note: Since PHP 4.2.0, the random number generator is no longer needed to be planted using the srand () or mt_srand () function, which is now automatically completed.
Note: In versions earlier than 3.0.7, max indicates range. To obtain a random number from 5 to 15 in these versions, the short example is rand (5, 11 ).