random_int
Returns a random integer from a range.
Available since: PHP 7.0
Syntax
random_int(int $min, int $max): intParameters
| Parameter | Type | Description |
|---|---|---|
| $min | int | The lower bound, inclusive. |
| $max | int | The upper bound, inclusive. |
Return value
intA random number from `$min` to `$max`.
Examples
Rolling a die — the result differs on every run:
<?php
echo random_int(1, 6);A random element of an array:
<?php
$colors = ['red', 'green', 'blue'];
echo $colors[random_int(0, count($colors) - 1)];Notes
Both bounds are included in the range. The numbers are cryptographically secure, so the function suits passwords and confirmation codes as well.
See also
Related recipes
In the tutorial
- Operators — Arithmetic, comparison and logical operators in PHP, and operator precedence.