mt_rand() generates a pseudo-random integer, optionally within an inclusive range. Do not use it for passwords, tokens, or other values that must be unpredictable; use random_int() for those cases.
$roll = mt_rand(1, 6);
echo $roll;
echo mt_rand(10,100); // Output is 32
Syntax
int mt_rand(int $min, int $max)
| Parameter | DESCRIPTION |
|---|---|
| $min | Optional : Minimum range of random number to be generated. |
| $max | Optional : Maximum range of random number to be generated. |
The return value is an integer in the requested inclusive range. Without arguments, the range is from 0 to mt_getrandmax().
mt_rand() uses the global Mersenne Twister state. PHP recommends Random\Randomizer for newly written code and random_int() when values must be unpredictable.
echo mt_rand();
The output changes between runs and is bounded by mt_getrandmax().
mt_srand(100);
echo mt_rand(1, 100);
echo mt_rand(1, 100); // Repeatable for the same algorithm/version
$min = 0;
$max = 1;
echo $min + (mt_rand() / mt_getrandmax()) * ($max - $min); // Output: Random float between 0 and 1
mt_rand() is predictable and must not be used for passwords, session tokens, reset codes, or other secrets. Use random_int(), random_bytes(), or a secure Random\Randomizer instead.
$red = mt_rand(0, 255);
$green = mt_rand(0, 255);
$blue = mt_rand(0, 255);
echo sprintf("#%02x%02x%02x", $red, $green, $blue); // Output: Random hex color
$arr = [1, 2, 3, 4, 5];
shuffle($arr);
print_r($arr); // Output: Array elements in random order
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.