PHP mt_rand() Function
The PHP mt_rand() function returns a pseudo-random integer via the Mersenne Twister Random Number Generator. If it is called without optional min, max arguments then it returns a pseudo-random integer between 0 and mt_getrandmax(). When min and max arguments are used, then it returns a pseudo-random integer between min and max (inclusive).
This function is a replacement for the older rand() function as it produces random numbers four times faster than the average libc rand() provides.
Syntax
mt_rand(min, max)
Parameters
min |
Optional. Specify the lowest value to return. Default is 0. |
max |
Optional. Specify the highest value to return. Default is mt_getrandmax(). |
Return Value
Returns a pseudo random value between min (or 0) and max (or mt_getrandmax(), inclusive).
Example:
In the example below, mt_rand() function is used to generate pseudo-random values.
<?php //generate 10 pseudo-random value //between 0 and mt_getrandmax() for ($i = 1; $i <= 10; $i++) { echo mt_rand()."\n"; } ?>
The output of the above code will be:
891050976 1454312675 526089933 1105988187 196288407 1304475315 174115646 815557523 1131992279 1643596901
Example:
Consider one more example where optional parameters are used to generate pseudo-random values in a given range.
<?php //generate 10 pseudo-random value //between 50 and 100 for ($i = 1; $i <= 10; $i++) { echo mt_rand(50, 100)."\n"; } ?>
The output of the above code will be:
55 59 91 82 69 99 95 67 91 98
❮ PHP Math Reference