mt_rand(): generates a random integer using the Mersenne Twister algorithm

Generate a pseudo-random integer with mt_rand()

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)
ParameterDESCRIPTION
$minOptional : Minimum range of random number to be generated.
$maxOptional : 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.

Example

echo mt_rand();

The output changes between runs and is bounded by mt_getrandmax().

Legacy reproducible sequence with mt_srand()

mt_srand(100);
echo mt_rand(1, 100);
echo mt_rand(1, 100); // Repeatable for the same algorithm/version

Example: Generating Random Float Numbers

$min = 0;
$max = 1;
echo $min + (mt_rand() / mt_getrandmax()) * ($max - $min);  // Output: Random float between 0 and 1

Do not use mt_rand() for passwords or tokens

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.

Example: Generating Random Colors

$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

Example: Random Shuffle of an Array

$arr = [1, 2, 3, 4, 5];
shuffle($arr);
print_r($arr);  // Output: Array elements in random order

Math Functions mt_getrandmax(): maximum mt_rand() value random_int(): secure random integers


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer