Open In App

PHP rand() Function

Last Updated : 06 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to get the random number using the rand() function in PHP, along with knowing its implementation through the example. The rand() is an inbuilt function in PHP used to generate a random number ie., it can generate a random integer value in the range [min, max].

Syntax:

rand();

The rand() function is used to generate a random integer. To generate a random integer in some range: 

Syntax:

rand(min,max);

Parameter values:

  • min: It is an optional parameter that specifies the lowest value that will be returned. The default value is 0.
  • max: It is an optional parameter that specifies the highest value to be returned. The default value is getrandmax().

Return value: This function will return the random integer values ranging from min to getrandmax(), including the max value.

Note: If the min and max value is not specified, default is 0 and getrandmax() respectively.

Example: In this example, we will use the rand() function that will return a random integer between 0 and getrandmax(). The rand(15,35) will return a random integer in the range [15,35].

PHP




<?php
      // Generating a random number
      $randomNumber = rand();
      print_r($randomNumber);
      print_r("\n");
 
      // Generating a random number in a
      // Specified range.
      $randomNumber = rand(15,35);
      print_r($randomNumber);
?>


Note: The output of the code may change every time it is run. So the output may not match with the specified output. 

Output:

1257424548
28

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads