PHP Mt_srand sowing a better random number generator seed
Mt_srand
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
Mt_srand--Sowing a better random number generator seed
Description
void Mt_srand (int seed)
Use seed to sow the random number generator. Starting with PHP version 4.2.0, the seed parameter becomes optional and is set to a number of times when the item is empty.
Example 1. Mt_srand () example
Code
Seed with microseconds
function Make_seed ()
{
List ($usec, $sec) = explode (' ', Microtime ());
return (float) $sec + ((float) $usec * 100000);
}
Mt_srand (Make_seed ());
$randval = Mt_rand ();
?>
Note: Since PHP 4.2.0, it is no longer necessary to use the Srand () or Mt_srand () function to sow the random number generator, which is now done automatically.
See Mt_rand (), Mt_getrandmax (), and Srand ().
PHP Mt_rand () function
Definition and usage
Mt_rand () returns a random integer using the Mersenne Twister algorithm.
Grammar
Mt_rand (min, max)
Description
If no optional parameter min and Max,mt_rand () are provided, the pseudo-random number between 0 and Rand_max is returned. For example, want a random number between 5 and 15 (including 5 and 15), with Mt_rand (5, 15).
Many of the old libc random number generators have some uncertainties and unknown characteristics and are slow. The rand () function of PHP uses the libc random number generator by default. The Mt_rand () function is informally used to replace it. The function uses the known characteristics of the Mersenne Twister as a random number generator, which can produce random values four times times faster than Rand () provided by LIBC.
Hints and Notes
Note: Since PHP 4.2.0, it is no longer necessary to sow the random number generator with the Srand () or Mt_srand () function, which is now done automatically.
Note: In the previous version of 3.0.7, Max means range. To get the same random number from the previous example of 5 to 15 in these versions, the short example is Mt_rand (5, 11).
Example
In this case, we will return some random numbers:
The output is similar to:
3150906288 513289678 35
Note: The above function gives a random integer, the characters outside the number will not come out, if you want to produce other characters, you need another custom method, as follows:
Code
/*
* $length: The length of the random number string
* $type: Types that generate random numbers
* */
function random ($length, $type = "") {
$chars =! $type? "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ": "0123456789abcdef";
$max = strlen ($chars)-1;
Mt_srand (Double) microtime () * 1000000);
for ($i = 0; $i < $length; $i + +) {
$string. = $chars [Mt_rand (0, $max)];
}
return $string;
}
$var = random (+, ' haha ');
Echo ($var);
?>
Output:
Fe61e294e5f46437cb3a92b92643ead6