srand()
Today, we will discuss the srand() function in PHP. This function is used to seed the random number generator.
The srand() function in PHP was used to seed the random number generator. Important: This function was deprecated in PHP 7.1 and completely removed in PHP 8.0. This guide explains its legacy behavior and shows how to achieve the same results with modern PHP.
What is the srand() Function?
The srand() function was a built-in PHP function that initialized the random number generator with a specific seed value. It accepted an optional $seed integer parameter and returned void. When a seed is provided, the generator produces a predictable sequence of numbers, which is useful for testing or reproducible simulations.
How to Use the srand() Function (Legacy PHP < 7.1)
Using srand() in older PHP versions was straightforward. Here is how it worked:
⚠️ Deprecation Notice: This example is for legacy PHP environments (versions prior to 7.1). Running this code on PHP 7.1+ will result in a fatal error.
Legacy Example
In this example, srand(123) initializes the generator. Subsequent calls to rand() will produce the exact same sequence of numbers every time the script runs with that seed. This determinism — not randomness — was the whole point of seeding: it let you reproduce a "random" sequence on demand for unit tests, game replays, or debugging.
Calling srand() with no argument (or, in PHP 4.2.0+, never calling it at all) seeded the generator from a hard-to-predict value, so each run produced a different sequence.
Modern PHP Alternatives
Since srand() and rand() are removed in PHP 8.0, use the following modern functions instead:
random_int(): Recommended for most use cases. It generates cryptographically secure random integers and does not require manual seeding.mt_rand(): Faster thanrandom_int()but not cryptographically secure. PHP 7.1+ automatically seeds the Mersenne Twister algorithm, so manual seeding is rarely needed.
If you still need a reproducible sequence for testing — the original reason to use srand() — seed the Mersenne Twister generator explicitly with mt_srand() before calling mt_rand(). To find the largest value these functions can return, see mt_getrandmax().
Modern Example
<?php
// Generate a cryptographically secure random integer between 1 and 100
$result = random_int(1, 100);
echo $result;
?>Conclusion
The srand() function is a legacy tool that has been removed from modern PHP. For current projects, use random_int() for secure random numbers or mt_rand() for general-purpose randomness. This guide should help you migrate legacy code and understand the modern approach to random number generation in PHP.