ProAnswers.org

How do you generate random numbers in PHP?

How do you generate random numbers in PHP?

Use the function "rand()" or "mt_rand()".

 

Both functions will generate a random number (as a return value, so be sure to make it point to a variable - see examples). However, "rand()" is slower and uses a default PHP randomizing system. mt_rand() is four times as fast, and uses the Mersenne Twister randomizing format - which is much more random.

 

Both functions have two optional parameters - a minimum integer and a maximum integer, respectively. By filling in these parameters, you will get a random number between the values you give (so, giving one and five will give you a random number that is no less than one, and no greater than five). These, again, are optional - and if left blank, the tiniest integer possible is no less than 0, and the largest integer possible is generated by the PHP function "getrandmax()" / "mt_getrandmax()" automatically.

 

Examples, of which all are acceptable:

 

/* Examples using no parameters */

 

$randomNumber = rand();

 

$randomNumber = mt_rand();

 

 

/* Examples using parameters */

 

$randomNumber = rand(1, 5);

 

$randomNumber = mt_rand(6, 10);

 

If your PHP build is version 4.2 or under, you will need to seed the random number generator with a value to base off of. "srand()" and "mt_srand()" (to be used with rand() and mt_rand() functions, respectively) can be used in this case. They both only have one optional parameter, which is any seed value - any number. If omitted, a random seed will be generated.

 

More acceptable examples:

 

// Example using no parameters

srand();

$randomNumber = rand();

 

// Example using the seed parameter

srand(12345);

$randomNumber = rand();

 

// Example using the "mt" random format functions (without parameters)

mt_Rand();

$randomNumber = mt_rand();

 

// Example using the "mt" random format (with parameters)

mt_rand(12345);

$randomNumber = mt_rand();