Generate 4 Digit Unique Random Numbers in PHP

In this tutorial, we will learn how to generate pseudo-random numbers in a particular range in PHP.


It is important to be aware that the following methods of generating numbers are not cryptographically secure.


The mt_rand() Function

The PHP mt_rand() function is an updated version of the original PHP rand() function. It uses the Mersenne Twister algorithm, is four times faster than the original and some dubious characteristics have been ironed out.


To use, mt_rand() pass the minimum number allowed as the first argument and maximum as the second. To generate 4 digit random numbers, set the range between 1000 and 9999 like this:


$four_digit_num = mt_rand(1000, 9999);


The rand() Function

If you are using a very old version of PHP, or for some other reason don't want to use the mt_rand() function, you can use the rand() function, which still works in the latest versions of PHP.


$four_digit_num = rand(1000, 9999);