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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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));
  
?>

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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;
?>

chevron_right


Output

Runtime Error

Exception Error :

  • Iinvalid parameter givesTypeError.
  • Invalid length of bytes givesError .
  • If source of randomness is not found then Exception will be thrown.

References:
http://php.net/manual/en/function.random-int.php

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai

Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.