PHP Reference ยท Math Functions
PHP mt_srand() function
Reference for PHP mt_srand() and srand(): seed the Mersenne Twister for reproducible random sequences, the effect on shuffle(), and its limits.
mt_srand() seeds the global Mersenne Twister generator used by mt_rand() and rand(). After seeding with the same integer, the generator produces exactly the same sequence of numbers, which is what you want for repeatable tests, procedurally generated game levels and demonstrations.
You never need to call it for ordinary randomness: PHP seeds the generator automatically with a secure random value the first time it is needed. srand() is simply an alias of mt_srand().
<?php mt_srand(42); echo mt_rand(1, 100); // the same number on every run
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
mt_srand(int $seed = 0, int $mode = MT_RAND_MT19937): void srand(int $seed = 0, int $mode = MT_RAND_MT19937): void
| Name | Description |
|---|---|
$seed |
The integer seed. If you omit it, PHP picks a random seed. |
$mode |
MT_RAND_MT19937 (default, correct algorithm) or the legacy MT_RAND_PHP, which is deprecated since PHP 8.3. |
Return value: nothing (void).
Usage notes
- Reproducible only on the same PHP version. The Mersenne Twister output for a given seed is stable across modern versions, but how
mt_rand($min, $max)maps values to a range or howshuffle()consumes numbers has changed between releases. Do not rely on exact values across upgrades. - Global state. Seeding affects every later call to
mt_rand(),rand(),shuffle(),str_shuffle()andarray_rand(). Code in libraries that also draws random numbers will shift your sequence. A privateRandom\Randomizerwith its own seeded engine avoids this. - Not for security. A guessable integer seed makes the output entirely predictable. Use
random_int()for secrets, which ignores the seed. MT_RAND_PHPis deprecated. It reproduced a flawed implementation from PHP 5; only use it to replay old data.- PHP 8.2 note:
shuffle(),str_shuffle()andarray_rand()use the global seeded generator, so they followmt_srand().