PHP mt_srand() Function
The PHP mt_srand() function is used to seed the Mersenne Twister random number generator with seed or with a random value if no seed is given.
Please note that there is no need to seed the random number generator with srand() or mt_srand() as this is done automatically.
Syntax
mt_srand(seed, mode)
Parameters
seed |
Optional. Specify an int seed value. |
mode |
Optional. Specify one of the following constants to specify the implementation of the algorithm to use:
|
Return Value
None.
Example:
In the example below, mt_srand() function is used to seed the Mersenne Twister random number generator with random value (although it is not required as this is done automatically in PHP).
As the seed value is random, it produces different results in each execution.
<?php //seed with microseconds function make_seed() { list($usec, $sec) = explode(' ', microtime()); return $sec + $usec * 1000000; } mt_srand(make_seed()); //generate 10 pseudo-random value //between 0 and mt_getrandmax() for ($i = 1; $i <= 10; $i++) { echo mt_rand()."\n"; } ?>
The output of the above code will be:
497858465 1959735385 1154191687 1151499995 496699632 293601299 1171312086 2047832089 575517256 1496918497
Example:
Consider one more example where seed value is fixed. This facilitates the ability to reproduce the same result in each execution.
<?php //seed with fixed value mt_srand(10); //generate 10 pseudo-random value //between 0 and getrandmax() for ($i = 1; $i <= 10; $i++) { echo mt_rand()."\n"; } ?>
The output of the above code will be:
1656398468 641584702 44564466 1062123783 1360749216 951367352 1608044093 1786516046 1070535660 1252673902
❮ PHP Math Reference