PHP Reference ยท Math Functions
PHP rand() and mt_rand() functions
Reference for PHP rand() and mt_rand(): generate pseudo-random integers, ranges, getrandmax(), seeding and why they are not secure.
mt_rand() returns a pseudo-random integer from the Mersenne Twister generator. Without arguments it gives a number between 0 and mt_getrandmax() (2147483647). With $min and $max it returns an integer in that range, both ends included. rand() is an older name for the same generator: since PHP 7.1 it is an alias of mt_rand(), with one difference described below.
These functions are fast and good for games, shuffling a playlist or sampling test data. They are not secure: the sequence can be predicted once enough values are seen. For tokens, passwords or anything an attacker would gain from guessing, use random_int() or random_bytes().
<?php echo mt_rand(1, 6); // a die roll echo mt_getrandmax(); // 2147483647
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
mt_rand(): int mt_rand(int $min, int $max): int rand(): int rand(int $min, int $max): int mt_getrandmax(): int getrandmax(): int
| Name | Description |
|---|---|
$min |
Lowest value that may be returned. |
$max |
Highest value that may be returned. Must not be lower than $min for mt_rand(). |
Return value: an int.
Errors: mt_rand() throws a ValueError when $max is less than $min, or when only one argument is given (ArgumentCountError).
Usage notes
- Not cryptographically secure. Never use it for password resets, session IDs, API keys, lottery draws with money at stake or CSRF tokens. Use
random_int(). - Seeding is automatic. PHP seeds the generator from a secure source on first use. Call
mt_srand()only for reproducible sequences, such as tests. rand()is the legacy spelling.rand($min, $max)accepts a reversed range and uses an older scaling for compatibility;mt_rand()is stricter and unbiased. Prefermt_rand()in new code.- Both ends are included:
mt_rand(1, 6)can return 1 and 6. lcg_value()is deprecated since PHP 8.4. For floats,mt_rand() / mt_getrandmax()gives a fraction that can be exactly 1. Userandom_int()orRandom\Randomizer::getFloat()for cleaner intervals.- Modern alternative: the
Random\Randomizerclass works with seedable engines and does not touch global state.