Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

random_int

Returns a random integer from a range.

Available since: PHP 7.0

Syntax

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

Parameters

ParameterTypeDescription
$minintThe lower bound, inclusive.
$maxintThe 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

  • max — Returns the largest of the given values.
  • round — Rounds a number to a given number of digits.

Related recipes

In the tutorial

  • Operators — Arithmetic, comparison and logical operators in PHP, and operator precedence.

Thanks for reading!

Donate to the site — we work hard for you.