PHP rand() Function (With Examples)

In this tutorial, we will learn about the PHP rand() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP rand() Function

The rand() function is used to generate random number in PHP, it is an in-built function and can be used to get any random number between given range.

Syntax

The syntax of the rand() function:

rand(min, max);

Parameters

The parameters of the rand() function:

  1. min – defines the minimum range of the random number.
  2. max – defines the maximum range of the random number.

Return Value

The return type of this method is int, it returns a pseudo random value between min (or 0) and max.

Note

If we do not specify ranges, rand() will generate random number from 0 to getrandmax().

PHP rand() Function Example

<?php
//Generating random number from 0 to genrandmax()
$num = rand();
print_r('Random number is: ' . $num . "\n");
//second time
$num = rand();
print_r('Random number is: ' . $num . "\n");

//Generating random number from 100 to 200
$num = rand(100,200);
print_r('Random number is: ' . $num . "\n");    
//second time
$num = rand(100,200);
print_r('Random number is: ' . $num . "\n");        
?>

Output

The output of the above example is:

Random number is: 1399397815
Random number is: 453651028
Random number is: 175
Random number is: 185

To understand the above example, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.