srand()
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
<?php
// Seed the random number generator using the srand() function
srand(123);
// Generate a random number using the rand() function
$result = rand();
// Output the result
echo $result;
?>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.
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.
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.
Practice
What function is srand() in PHP?