[Previous] [Contents] [Next]

Random Number Generation

PHP provides the function rand( ), which returns values from a generated sequence of pseudo-random numbers. Well-known algorithms generate sequences that appear to have random behavior but aren't truly random. The srand( ) function seeds the algorithm and needs to be called before the first use of the rand( ) function in a script. Otherwise, the function returns the same numbers each time a script is called. The prototypes of the functions are:

void srand(integer seed)
integer rand(  )
integer rand(integer min, integer max)

srand function

The pseudo-random number generator is initialized using the argument passed as seed. For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.

Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand.

If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand or srand.

In order to generate random-like numbers, srand is usually initialized to some distinctive runtime value, like the value returned by function time. This is distinctive enough for most trivial randomization needs.

The srand( ) function is called by passing an integer seed that is usually generated from the current time.

rand function

When called with no arguments, rand( ) returns a random number between 0 and the value returned by getrandmax( ). When rand( ) is called with two arguments-the min and max values-the returned number is a random number between min and max. Consider this example:

// Generate a seed.
$seed = (float) microtime(  ) * 100000000;
// Seed the pseudo-random number generator
// Generate some random numbers
print rand();      // between 0 and getmaxrand(  )
print rand(1, 6);  // between 1 and 6 (inclusive)

[Previous] [Contents] [Next]