PHP program to generate a random number in a given range (min, max)

PHP

Using the rand() function: The rand() function generates a pseudo-random number between a given range, or between 0 and the default maximum (getgrandmax()), which is system dependent.Syntax:
int rand ($min, $max) 
Parameters:the rand() function takes two optional parameters as above and described below.
  • $min: is an optional parameter used to set the lower limit for the random number. The default min is 0.
  • $max:This is an optional parameter used to set an upper limit for the random number. The default is max - this is the return value of getgrandmax(), which is system dependent (for Windows it is 32767).
Program 1:PHP program to generate a random number using the rand function().
// PHP program for generating a random number
// within the specified range 
// Generate random numbers without a range
// the rand() function returns a random number $num1 = rand(); echo " Random number: " . $num1 . "" ;  
// Generate random numbers in a given range $num2 = rand (7, 100); echo "Random number in range (7, 100):" , $num2 ;  
?>
Exit:
Random number: 77551982 Random number in range (7, 100): 37 
Note.The rand() function - it is a pseudo-random function which means that it takes a seed from the machine and generates a number according to it. Thus, the method for generating numbers is not completely random. This can be tracked to a certain extent. So it is not cryptographically secure. It is not used for cryptography where randomization is very important. Use the random_int() function to generate a cryptographically secure random number. Using the random_int() function: random_int() is used to generate cryptographically secure random numbers. These numbers can be used for objective results. CryptGenRandom() function on Windows and getrandom (2) system call on Linux to generate a random number.Syntax:
int random_int ($min, $max) 
Parameters:The random_int() function takes two parameters as above and described below.
  • $min: contains the lower limit of the random number.
  • $max:contains the upper limit of the random number.
Program 2: Generate random numbers in a range using the random_int() function.
// PHP program for generating a random number
// in a given range 
// Generate random numbers in a given range
// using the random_int() function $num1 = random_int (35 , 100); echo " Random number in range (35, 100): " . $num1 . "" ;  
// Random number in the range (10, 30) $num2 = random_int (10, 30); echo " Random number in range (10, 30): " . $num2 ;  
?>
Exit:
Random number in range (35, 100): 93 Random number in range (10, 30): 28 




Get Solution for free from DataCamp guru