rand

rand -- generate a random value

Description

int rand(void );

Returns a pseudo-random value between 0 and RAND_MAX. If you want a random number between 5 and 15, for example, use rand()%10 + 5.

Remember to seed the random number generator before use with srand().

Here are two handy functions that use rand(). One returns a random integer less than a specified maximum value, the other does the same but returns a real value.

Example 1. rand example functions

function randomint($max = 100) { 
    static $startseed = 0; 
    if (!$startseed) {
        $startseed = (double)microtime()*getrandmax(); 
        srand($startseed);
    } 
    return (rand()%$max); 
} 

function random($max = 1) { 
    static $startseed = 0; 
    if (!$startseed) { 
        $startseed = (double)microtime()*getrandmax();
        srand($startseed); 
    }
    return ((rand()/getrandmax())*$max); 
}
	

See also srand() and getrandmax().