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.

Updated on: 2026-03-15T07:29:18+05:30

124 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements