PHP Function Reference

PHP srand() Function



The PHP srand() function is used to seed the random number generator with seed or with a random value if no seed is given.

Please note that there is no need to seed the random number generator with srand() or mt_srand() as this is done automatically.

Syntax

srand(seed)

Parameters

seed Optional. Specify an int seed value.

Return Value

None.

Example:

In the example below, srand() function is used to seed the random number generator with random value (although it is not required as this is done automatically in PHP).

As the seed value is random, it produces different results in each execution.

<?php
//seed with microseconds
function make_seed() {
  list($usec, $sec) = explode(' ', microtime());
  return $sec + $usec * 1000000;
}
srand(make_seed());

//generate 10 pseudo-random value
//between 0 and getrandmax()
for ($i = 1; $i <= 10; $i++) {
  echo rand()."\n";
}
?>

The output of the above code will be:

1489097103
52646159
417163374
1140338404
932967394
1793355896
158034244
1981207412
2115064440
2013356126

Example:

Consider one more example where seed value is fixed. This facilitates the ability to reproduce the same result in each execution.

<?php
//seed with fixed value
srand(10);

//generate 10 pseudo-random value
//between 0 and getrandmax()
for ($i = 1; $i <= 10; $i++) {
  echo rand()."\n";
}
?>

The output of the above code will be:

1656398468
641584702
44564466
1062123783
1360749216
951367352
1608044093
1786516046
1070535660
1252673902

❮ PHP Math Reference