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
PHP mt_srand() Function
The mt_srand() function seeds the Mersenne Twister random number generator in PHP. The prefix 'mt' stands for Mersenne Twister, which is a high−quality pseudorandom number generator algorithm. While seeding is optional in PHP (done automatically), manual seeding ensures reproducible random sequences or better randomization.
Syntax
mt_srand ([ int $seed [, int $mode = MT_RAND_MT19937 ]] ) : void
Parameters
| Parameter | Description |
|---|---|
| seed (optional) | Integer value used as seed. If omitted, a random number is used |
| mode (optional) |
MT_RAND_MT19937: Uses fixed Mersenne Twister implementation MT_RAND_PHP: Uses default PHP implementation |
Return Value
This function does not return any value (void).
Examples
Basic Seeding with Current Time
Using the current timestamp ensures different random sequences each run −
<?php
mt_srand(time());
echo "Random number: " . mt_rand();
?>
Random number: 1847236925
Fixed Seed for Reproducible Results
Using a fixed seed generates the same sequence every time −
<?php
mt_srand(12345);
echo "First: " . mt_rand() . "<br>";
echo "Second: " . mt_rand() . "<br>";
// Reset with same seed
mt_srand(12345);
echo "Reset First: " . mt_rand() . "<br>";
?>
First: 1914388016 Second: 1289118564 Reset First: 1914388016
Comparing Different Modes
Demonstrating the difference between MT_RAND_MT19937 and MT_RAND_PHP modes −
<?php
// Using MT19937 mode
mt_srand(1000, MT_RAND_MT19937);
echo "MT19937: " . mt_rand() . "<br>";
// Using PHP default mode
mt_srand(1000, MT_RAND_PHP);
echo "PHP mode: " . mt_rand();
?>
MT19937: 1244898303 PHP mode: 1244898303
Conclusion
The mt_srand() function provides control over random number generation seeding. Use fixed seeds for reproducible results in testing, or time−based seeds for true randomization in production applications.
