Tutorialspoint.dev

PHP | gmp_random_range() Function

The gmp_random_range() is an inbuilt function in PHP which generates a random number.The random number thus generated lies between range min to max. Here GMP refers to (GNU Multiple Precision) which is for large numbers.

Syntax:

gmp_random_range ( GMP $min, GMP $max )

Parameters: The function accepts two parameters, GMP $min number representing lower bound for the random number and GMP $max number to represent the upper bound of the random number. This parameter can be a GMP object in PHP version 5.6 and later, or we are also allowed to pass a numeric string provided that it is possible to convert that string to a number.

Return Value: The function returns a random GMP number in the range $min-$max.

Examples:



Input : lower bound=0, upper bound =100
Output :  25

Input : lower bound=-100, upper bound=-10
Output :  -23 

Note:Output will vary every time on execution

Below programs illustrate the use of gmp_random_range() function:

Program 1: The program below demonstrates the working of gmp_random_range() function when numeric strings are passed as arguments.

<?php
// PHP program to demonstrate the gmp_random_range() function 
  
// numeric string as arguments
$min = "-200";
$max = "-100";
  
  
$rand = gmp_random_range($min, $max); 
  
echo $rand;
?>

Output:

-165

Program 2: The program below demonstrates the working of gmp_random_range() when GMP number is passed as an argument.

<?php
// PHP program to demonstrate the gmp_random_range() function 
  
// GMP numbers as arguments
$min = gmp_init("1000", 2);
$max = gmp_init("1000000", 2); 
  
  
$rand = gmp_random_range($min, $max); 
  
// gmp_strval converts GMP number to string 
// representation in given base(default 10).
echo gmp_strval($rand) . " ";
?>

Output:

30

Reference:
http://php.net/manual/en/function.gmp-random-range.php



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter