Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
mt_srand() function in PHP
The mt_srand() function seeds the Mersenne Twister random number generator in PHP. This function allows you to initialize the random number generator with a specific seed value, ensuring reproducible random number sequences.
Note − Random number generator is seeded automatically after the release of PHP 4.2.0. This function is not needed now unless you want predictable random sequences.
Syntax
mt_srand(seed)
Parameters
seed − Optional integer value used to initialize the random number generator. If omitted, a random seed is used.
Return Value
The mt_srand() function returns nothing (void).
Example 1: Basic Usage with mktime()
Using mktime() to generate a time-based seed −
<?php
mt_srand(mktime());
echo mt_rand();
?>
1320295657
Example 2: Fixed Seed for Reproducible Results
Using a fixed seed to generate the same sequence every time −
<?php
// Using fixed seed
mt_srand(12345);
echo "First run: " . mt_rand(1, 100) . "<br>";
echo "Second run: " . mt_rand(1, 100) . "<br>";
// Reset with same seed
mt_srand(12345);
echo "After reset: " . mt_rand(1, 100) . "<br>";
?>
First run: 41 Second run: 54 After reset: 41
Conclusion
While mt_srand() is rarely needed in modern PHP, it's useful when you need reproducible random sequences for testing or when you want to control the randomness. For most applications, PHP's automatic seeding is sufficient.
