PHP Reference ยท Math Functions
PHP random_int() function
Reference for PHP random_int(): generate cryptographically secure random integers in a range, how it differs from mt_rand(), errors and typical uses.
random_int() returns a uniformly distributed random integer between $min and $max, both inclusive. It draws from the operating system's cryptographically secure random source, so the result cannot be predicted from earlier values. Use it whenever guessing the number would hurt: one-time codes, shuffling in a lottery, picking a salt position, or generating tokens from an alphabet.
The function cannot be seeded and has no reproducible sequence. That makes it unsuitable for tests that need the same numbers every run; use mt_srand() or a seeded Random\Randomizer for that.
<?php echo random_int(1, 6); // 1 to 6, secure echo random_int(PHP_INT_MIN, PHP_INT_MAX);
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
random_int(int $min, int $max): int
| Name | Description |
|---|---|
$min |
Lowest possible value. |
$max |
Highest possible value. |
Return value: an int in the range $min to $max, inclusive. The result is uniform: every value is equally likely.
Errors: a ValueError if $min is greater than $max. A Random\RandomException if no secure source of randomness is available (very rare).
Usage notes
- Secure by design. It uses the system CSPRNG (
getrandom(),/dev/urandom, or the OS equivalent). Calling code does not need to seed anything. - No modulo bias. Unlike
random_bytes() % n,random_int()rejects out-of-range draws internally, so small ranges stay uniform. - Reversed ranges throw, unlike the legacy
rand()which silently swaps them. - Slower than
mt_rand(), but the cost is negligible unless you draw millions of numbers in a hot loop. - Floats: there is no
random_float(); useRandom\Randomizer::getFloat()(PHP 8.3+) or compute a fraction from integers. - Not reproducible. Calling
mt_srand()has no effect on it. - Exception class:
Random\RandomExceptionwas added in PHP 8.2; earlier versions threw a plainException.