mt_rand()

mt_rand() — Generate a random value via the Mersenne Twister Random Number Generator.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Many random number generators of older libcs have dubious or unknown characteristics and are slow. The mt_rand() function is a drop-in replacement for the older rand(). It uses a random number generator with known characteristics using the Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.

Signature

mt_rand(): int mt_rand(int $min, int $max): int

Parameters

ParameterTypeWhat it takes
$minintOptional lowest value to be returned (default: 0)
$maxintOptional highest value to be returned (default: mt_getrandmax())

Return value

A random integer value between min (or 0) and max (or mt_getrandmax(), inclusive).

Example

A runnable snippet:

echo mt_rand(), "\n"; echo mt_rand(), "\n"; echo mt_rand(5, 15), "\n";

Output:

1604716014 1478613278 6

Changelog

VersionChange
8.0.0A ValueError will be thrown if max is less than min; previously an E_WARNING was raised, and the function returned false.
7.2.0mt_rand() has received a bug fix for a modulo bias bug. This means that sequences generated with a specific seed may differ from PHP 7.1 on 64-bit machines.
7.1.0rand() has been made an alias of mt_rand().
7.1.0mt_rand() has been updated to use the fixed, correct, version of the Mersenne Twister algorithm. To fall back to the old behaviour, use mt_srand() with MT_RAND_PHP as the second parameter.

See also

mt_srand(), mt_getrandmax(), random_int(), random_bytes()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page mt_rand() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.