W3docs

mt_srand()

Today, we will discuss the mt_srand() function in PHP. This function is used to seed the random number generator used by the mt_rand() function.

Today, we will discuss the mt_srand() function in PHP. This function seeds the random number generator used by mt_rand(). Note: mt_srand() is deprecated as of PHP 8.1 and removed in PHP 8.4. For modern PHP applications, use random_int() or random_bytes() instead.

What is the mt_srand() Function?

The mt_srand() function initializes the Mersenne Twister random number generator with a specific seed value. When a fixed seed is provided, mt_rand() produces a predictable, reproducible sequence of numbers. This deterministic behavior is primarily useful for testing, debugging, or scenarios where consistent random output is required.

How to Use the mt_srand() Function

Using mt_srand() is straightforward. Here is a basic example:

How to Use the mt_srand() Function in PHP?

php— editable, runs on the server

In this example, mt_srand(12345) sets the generator's seed. Subsequent calls to mt_rand() will produce the same output across different runs because the seed remains constant. The result is stored in $result and printed to the screen.

Version compatibility note: In PHP 8.1+, this code will trigger a deprecation warning. For PHP 8.4+ and modern projects, replace mt_srand()/mt_rand() with random_int() for secure and supported random number generation.

The Modern Replacement

mt_srand() exists to make randomness reproducible by fixing a seed. The modern, cryptographically secure functions intentionally cannot be seeded — you get unpredictable values every time:

<?php
// Modern, secure replacement — no seeding required
$result = random_int(1, 100); // a secure random integer between 1 and 100 (inclusive)

echo $result;
?>

Because random_int() draws from the operating system's cryptographically secure source, you should use it for anything security-sensitive (tokens, passwords, one-time codes). The trade-off is that you lose reproducibility: there is no seed to set, so the same code never produces the same number twice.

If you genuinely need a reproducible sequence (for example, generating the same test fixtures on every run) in PHP 8.2+, use the seedable, object-based \Random\Randomizer with the Mt19937 engine instead of the deprecated mt_srand().

Conclusion

While mt_srand() provides deterministic random sequences for legacy code or specific testing needs, it is deprecated in PHP 8.1 and removed in PHP 8.4. Modern PHP development should rely on random_int() or random_bytes() for secure and supported random number generation. We hope this guide clarifies the historical context and proper usage of mt_srand() in older PHP environments.

Practice

Practice
What is the purpose of the mt_srand() function in PHP?
What is the purpose of the mt_srand() function in PHP?
Was this page helpful?