PHP srand() Function

The srand() function is used to seed the random number generator in PHP. Seeding initializes the random number generator with a specific starting value, ensuring reproducible or truly random sequences. While seeding is done automatically in modern PHP versions, manual seeding gives you control over randomization.

Syntax

srand([ int $seed ]) : void

Parameters

Parameter Description Required
seed An integer to be used as seed. If not provided, a random number is used automatically Optional

Return Value

This function doesn't return any value (void).

Examples

Basic Usage with Time-based Seed

Using current time as seed to ensure different random sequences on each run −

<?php
    srand(time());
    echo "Random number 1: " . rand() . "<br>";
    echo "Random number 2: " . rand() . "<br>";
    echo "Random number 3: " . rand();
?>
Random number 1: 548287992
Random number 2: 1834728471
Random number 3: 927364851

Fixed Seed for Reproducible Results

Using a fixed seed to generate the same sequence every time −

<?php
    srand(12345);
    echo "First run:<br>";
    echo rand() . "<br>";
    echo rand() . "<br>";
    
    // Reset with same seed
    srand(12345);
    echo "\nSecond run (same seed):<br>";
    echo rand() . "<br>";
    echo rand();
?>
First run:
467541266
1318204805

Second run (same seed):
467541266
1318204805

Key Points

  • In modern PHP, seeding is automatic, making srand() optional
  • Use fixed seeds for testing and reproducible results
  • Use time-based seeds for truly random sequences
  • Consider using mt_srand() for better randomness

Conclusion

The srand() function provides control over PHP's random number generation by setting the initial seed value. Use it when you need reproducible sequences for testing or when you want to ensure different random sequences in each program execution.

Updated on: 2026-03-15T08:59:28+05:30

404 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements