Home > Article > Backend Development > Summary of methods for generating random numbers using PHP built-in functions
PHP’s internal method of generating random numbers is simpler than other methods and does not require additional configuration. It is the preferred solution for generating random numbers.
1. rand function
rand() function can generate random integers without adding any parameters. If you want to set the range of random numbers, you can set the values of min and max in the function. If you need to generate a random number seed, use the srand function configuration.
echo rand(); // 生成 0~RAND_MAX 之间的随机数,Windows 系统下 RAND_MAX 的值为 32767,RAND_MAX 可以用函数 getrandmax() 获得 echo rand(1000000, 9999999); // 生成 1000000~9999999 之间的随机数 $seed = time(); // 使用时间作为种子源 srand($seed); // 播下随机数发生器种子 echo rand(); // 根据种子生成 0~32768 之间的随机数。如果 $seed 值固定,则生成的随机数也不变 echo rand(1000000, 9999999); // 根据种子生成 1000000~9999999 之间的随机数。如果 $seed 值固定,则生成的随机数也不变
2. mt_rand function
mt_rand() uses the Mersenne Twister algorithm to return random integers. The main difference from the rand() function is that mt_rand() generates random numbers. Numerics are on average four times faster than the rand() provided by libc, and the seeding function uses mt_srand() instead of srand(). Although there is this difference, their usage methods are still similar, as follows:
echo mt_rand(); // 生成 0~RAND_MAX 之间的随机数,Windows 系统下 RAND_MAX 的值为 2147483647(与rand()中的 RAND_MAX 不同),RAND_MAX 可以用函数 mt_getrandmax() 获得 echo mt_rand(1000000, 9999999); // 生成 1000000~9999999 之间的随机数,不受系统 RAND_MAX 影响 $seed = time(); // 使用时间作为种子源 mt_srand($seed); // 播下随机数发生器种子 echo rand(); // 根据种子生成 0~RAND_MAX 之间的随机数,如果 $seed 值固定,则生成的随机数也不变 echo rand(1000000, 9999999); // 根据种子生成 1000000~9999999 之间的随机数,如果 $seed 值固定,则生成的随机数也不变
Note: The random numbers generated by rand() and mt_rand() are all integers and will not contain English letters.
3. uniqid function
The uniqid() function generates a unique ID based on the current time in microseconds. The length of the default generated ID is 13 or 23 digits, consisting of English letters and numbers. The uniqid() function has two parameters, in the following format:
uniqid(prefix,more_entropy)
Among them,
prefix: the prefix of the generated ID
more_entropy: whether to add additional entropy
The following program,
echo uniqid(); // 生成13位字符串,如:55f540e273e93 echo uniqid('one.'); // 生成前缀为one.加13位随机字符的字符串,如:one.55f540e273e93 echo uniqid('two.', true); // 生成前缀为two.加23位随机字符的字符串(加了熵),如:two.55f540e273e932.77804707,比上面的多了 10 位,即多了:2.77804707
Explanation: Because it is based on system time, the ID generated by this function is not optimal. To generate an absolutely unique ID, use the md5() function.
The above is the detailed content of Summary of methods for generating random numbers using PHP built-in functions. For more information, please follow other related articles on the PHP Chinese website!