php8.5
Home/ Manual/ random / functions/ random_int

random_int

PHP function Edit on GitHub ✎

(PHP 7, PHP 8)

Get a cryptographically secure, uniformly selected integer

Description

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

Generates a uniformly selected integer between the given minimum and maximum.

The randomness generated by this function is suitable for all applications, including the generation of long-term secrets, such as encryption keys.

Sources Backport

Parameters

min

The lowest value to be returned.

max

The highest value to be returned.

Return Values

A cryptographically secure, uniformly selected integer from the closed interval [min, max]. Both min and max are possible return values.

Errors/Exceptions

  • If max is less than min, a ValueError will be thrown.

Changelog

VersionDescription
8.2.0In case of a CSPRNG failure, this function will now throw a Random\RandomException. Previously a plain Exception was thrown.

Examples

random_int() example

php
<?php
var_dump(random_int(100, 999));
var_dump(random_int(-1000, 0));
?>

The above example will output something similar to:

output
int(248)
int(-898)

See Also

Source: reference/random/functions/random-int.xml · from the official PHP manual (php/doc-en)