PHP normally seeds the Mersenne Twister automatically. Call mt_srand() only when you intentionally need a repeatable pseudo-random sequence, such as a controlled demonstration; it is not a security mechanism.
mt_srand(1234);
echo mt_rand(1, 100);
Manual time-based seeding is unnecessary because PHP seeds the generator automatically.
Syntaxvoid mt_srand(?int $seed = null, int $mode = MT_RAND_MT19937)
| Parameter | DESCRIPTION |
|---|---|
| $seed | Optional : Seed used |
| $mode | Optional: use MT_RAND_MT19937. The legacy MT_RAND_PHP mode is deprecated as of PHP 8.3. |
Do not call mt_srand(time()) for normal random generation. PHP already initializes the global generator automatically.
<?php
mt_srand(123);
echo mt_rand(); // Same seed starts the same pseudo-random sequence for the same algorithm/version
?>
<?php
mt_srand(42);
for($i = 0; $i < 5; $i++) {
echo mt_rand() . "<br>";
}
?>
<?php
mt_srand(100);
echo mt_rand(); // Output: A specific pseudo-random number
mt_srand(200);
echo mt_rand(); // Output: A different specific pseudo-random number
?>
<?php
mt_srand(7);
$lottery_numbers = [];
for($i = 0; $i < 6; $i++) {
$lottery_numbers[] = mt_rand(1, 49);
}
echo implode(", ", $lottery_numbers); // Repeatable demonstration values; not suitable for a real lottery
?>
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.