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
// Seed the random number generator using the mt_srand() function
mt_srand(12345);
// Generate a random integer using the mt_rand() function
$result = mt_rand();
// Output the result
echo $result;
?>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.
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
What is the purpose of the mt_srand() function in PHP?