mt_srand(): Seeds the Mersenne Twister Random Number Generator

Seed mt_rand() only when reproducibility is intentional

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.

Syntax
void mt_srand(?int $seed = null, int $mode = MT_RAND_MT19937)
ParameterDESCRIPTION
$seedOptional : Seed used
$modeOptional: use MT_RAND_MT19937. The legacy MT_RAND_PHP mode is deprecated as of PHP 8.3.

Automatic seeding is normally sufficient

Do not call mt_srand(time()) for normal random generation. PHP already initializes the global generator automatically.

Example 2: Using a Fixed Seed for Reproducibility

<?php
mt_srand(123);
echo mt_rand();  // Same seed starts the same pseudo-random sequence for the same algorithm/version
?>

Example 3: Generating a Sequence of Random Numbers with a Seed

<?php
mt_srand(42);
for($i = 0; $i < 5; $i++) {
    echo mt_rand() . "<br>";
}
?>

Example 4: Resetting the Seed with Different Values

<?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
?>

Example 5: Repeatable demonstration data

<?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
?>

Math Functions mt_rand(): Mersenne Twister integers random_int(): secure random integers


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer