PHP | random_int() Function
The random_int () is an inbuilt function in PHP. The main function is to generate cryptographically secure pseudo-random integers value. When unbiased results occur in critical condition, then generated cryptographic random integers are used.
The different sources of randomness used in this function are given below :-
- Window : CryptGenRandom() function used.
- Linux : getrandom(2) system call function to be used.
Syntax :
int random_int ( $min, $max )
Parameter :
- $min : Returned lowest value , Which is equal to PHP_INT_MIN or higher.
- $max : Returned highest value , which is less than or equal to PHP_INT_MAX.
Return Value :A cryptographically secure random integer in range min to max inclusive.
Examples:
Input : min= 10, max=10000 Output : int(5183) Input : min= -244441, max= 1 Output : int(-60209)
Below programs illustrate the random_int() function in PHP.
Program 1:
<?php
// PHP program to demonstrate
// the random_int() function
// given min and max range
var_dump(random_int(1, 5555555));
var_dump(random_int(-1, 100000));
var_dump(random_int(9, 10));
?>
Output
int(835427) int(86695) int(10)
Below programs illustrate the random_int() function in PHP.
Program 2:
When write not valid range, then its comes runtime errors.
<?php
// PHP program to demonstrate
// the random_int() function
// given min and max range
// Not valid range
$t = (random_int(99, 11));
// Print result
echo "(int)", $t;
?>
Output
Runtime Error
Exception Error :
- invalid parameter givesTypeError.
- Invalid length of bytes givesError .
- If source of randomness is not found then Exception will be thrown.
References:
https://www.php.net/manual/en/function.random-int.php