The Rand() PHP Function

Businesswoman working in the office

Zhang Bo / Getty Images

The rand() function is used in PHP to generate a random integer. The rand() PHP function can also be used to generate a random number within a specific range, such as a number between 10 and 30.

If no max limit is specified when using the rand() PHP function, the largest integer that can be returned is determined by the getrandmax() function, which varies by operating system. 

For example, in Windows, the largest number that can be generated is 32768. However, you can set a specific range to include higher numbers.

Rand() Syntax and Examples

The correct syntax for using the rand PHP function is as follows:

rand();

or

rand(min,max);

Using the syntax as described above, we can make three examples for the rand() function in PHP:

<?php
echo (rand(10, 30) . "<br>");
echo (rand(1, 1000000) . "<br>");
echo (rand());
?>

As you can see in these examples, the first rand function generates a random number between 10 and 30, the second between 1 and 1 million, and then third without any maximum or minimum number defined.

These are some possible results:

20
442549
830380191

Security Concerns Using Rand() Function

The random numbers generated by this function are not cryptographically secure values, and they should not be used for cryptographic reasons. If you need secure values, use other random functions such as random_int(), openssl_random_pseudo_bytes(), or random_bytes()

Note: Beginning with PHP 7.1.0, the rand() PHP function is an alias of mt_rand(). The mt_rand() function is said to be four times faster and it produces a better random value. However, the numbers it generates are not cryptographically secure. The PHP manual recommends using the random_bytes() function for cryptographically secure integers.