How to generate random numbers in PHP?

In your PHP application, you may be required to write an algo that generates random numbers that can be used for PINs, passwords, or some other purpose.

The PHP rand function generates a random number (integer) from zero to the maximum number returned by getrandmax() function. The maximum number in Windows platform can be (for example) 32768.

An example:

echo rand();

You may also specify a range for generating a random number e.g. 100 to 200. This is done by using the optional parameters in the rand function as shown in the syntax below.

int rand ( int $minimum , int $maximum )

Where $miinum number specifies the starting number for the random number to be generated. The $maximum specifies the highest number.

Both these parameters are optional, so you may omit and let the rand function generate a number.

The section below shows using rand function with and without parameters along with using rand multiple times for generating random numbers by the single statement – so keep reading.

The example of rand without parameters

In this example, the rand() PHP function is used without providing minimum or maximum numbers. The random number is simply displayed by using PHP echo statement:

The code:


echo "The random number without parameters: " .(rand());


As I executed this code in windows platform, the following was the output:

The random number without parameters: 26456

The number will change for every refresh of the web browser as you can see in the example page.

Using range for the random number

Now, I used the minimum and maximum parameters in the rand function. The random number should be between 50 to 500. This is how it is specified:


echo "The random number between 50-500: " .(rand(50,500));

Sample output:

The random number between 50-500: 129

Copy/Paste the above code to your editor and refresh the page to see what random number is displayed. This should be between 50 to 500 and change on every refresh.

Note: The 50 and 500 are inclusive in the above example.

A more usable example of rand function

In the following example, the rand function is used several times with different ranges for creating a number.

In that way, an accumulative number can be created based on certain rules. For example, the first part of the random code should be between 1-10. The second should be 100 to 1000 and then you may concatenate a fixed number etc.

PHP code:

$gen_random = 420 .rand(25,50) .rand(100,1000) .rand(1000,10000) ;

echo "Multiple rand number: " .$gen_random;


The output as ran this code on the local system:

Multiple rand numbers: 420338781727