In PHP, we often need to use random numbers to perform some operations. Sometimes we need the range of random numbers to be the same, but the random numbers generated each time are different. So, how to generate different random numbers?
We can use the timestamp of the current time as the seed for random number generation. The timestamp is the number of seconds from January 1, 1970 00:00:00 GMT to the current time. For example, we can use the following code to generate random numbers:
mt_srand(time()); $random_number = mt_rand(1, 100);
In the above code, mt_srand(time())
means using the current timestamp as the seed number, mt_rand(1, 100)
means generating a random number between 1 and 100.
We can use random string as random number seed. For example, we can use the following code to generate random numbers:
$seed = str_split('abcdefghijklmnopqrstuvwxyz' .'ABCDEFGHIJKLMNOPQRSTUVWXYZ' .'0123456789'); shuffle($seed); $random_number = ''; foreach (array_rand($seed, 10) as $k) { $random_number .= $seed[$k]; }
In the above code, we first split the string containing all possible characters into a character array $seed
, and then call shuffle
The function rearranges this array. Next, we use the array_rand
function to randomly select 10 characters from the array, and finally concatenate these characters together as a random number.
PHP’s uniqid
function can generate a unique ID, and we can also use it to generate random numbers. For example, we can use the following code to generate random numbers:
$random_number = uniqid(mt_rand(), true);
In the above code, the mt_rand()
function returns a random integer, which is used as the prefix of the uniqid
function , true
parameter indicates using microsecond timestamp as suffix.
Summary
Using timestamps, random characters and the uniqid
function can generate different random numbers. In actual use, you need to choose a method that suits you according to the specific situation. It should be noted that random numbers are not truly random numbers, but pseudo-random numbers that rely on a random number generator. Therefore, when truly secure random numbers are required, specialized cryptographic libraries are required.
The above is the detailed content of How to generate different random numbers in php. For more information, please follow other related articles on the PHP Chinese website!