How to generate random and unique number in PHP
Last updated: Aug 24, 2022
Colleagues hello to all.
In today's article, we'll talk about how to generate a set of random numbers in PHP.
When developing an application, we often face the fact that we need to generate a unique number. An example of this might be that you need to select random records from a database, or when uploading files to the server, we need to generate a unique filename that will contain a name only from numbers and so on. With each request to the application, it will be difficult for your server to generate unique numbers on its own, and our task is to help the server by providing a unique number for its further processing.
There are a lot of different ways to get a unique number in PHP, and we'll look at all of them today.
In the very first variant, we will use a classic function called rand. The rand function takes only two parameters min and max, the first parameter is the smallest number, the default is 0, the second parameter is the largest number. The function returns a unique number between the values of the min and max parameters of type int.
php> rand(0, 9000000000);
As you can see, as a result, we called the function rand three times, and for these three times the function returned three unique numbers.
In the next example, we will use the mt_rand function. The function also takes two parameters min and max and returns a unique number between the values of the parameters min and max of type int. The mt_rand function is considered an improved version of the rand function due to the fact that mt_rand generates a random number by the method of simple numbers based on the Whirlwind Mersenne.
php> mt_rand(0, 9000000000);
As you can see, we also got three unique numbers as a result.
The next option we will use is the random_int function. The function takes two parameters min and max and returns a unique integer between the values of min and max parameters of type int.
php> random_int(0, 1024);
And in this result we get three unique numbers.
As a final simple option, we can use the time. The time function returns the number of seconds from the start of the Unix epoch (January 1, 1970 00:00:00 GMT) to the current time. The time function is ideal for generating a unique ID for writing to a database.
As a result, colleagues, today we have analyzed four functions with which we can generate a unique number, and it is up to you to decide which function to use.
Thank you all, I hope that my article helped you in some way.