The way PHP generates unique numbers is through the mt_rand() function. Function syntax: [mt_rand(min,max)], such as [mt_rand(10,100)], means generating a random integer between 10 and 100 (inclusive).
#To generate unique numbers, you can use the mt_rand() function.
(Recommended tutorial: php tutorial)
Function introduction:
mt_rand() function uses the Mersenne Twister algorithm to generate random integers.
For example:
If you want a random integer between 10 and 100, inclusive, use mt_rand (10,100).
Function syntax:
mt_rand(); or mt_rand(min,max);
Parameter introduction:
min Optional. Specifies the minimum number to return. The default is 0.
max Optional. Specifies the maximum number to return. The default is mt_getrandmax().
Code implementation:
<?php /* * array unique_rand( int $min, int $max, int $num ) * 生成一定数量的不重复随机数,指定的范围内整数的数量必须 * 比要生成的随机数数量大 * $min 和 $max: 指定随机数的范围 * $num: 指定生成数量 */ function unique_rand($min, $max, $num) { $count = 0; $return = array(); while ($count < $num) { $return[] = mt_rand($min, $max); $return = array_flip(array_flip($return)); $count = count($return); } //打乱数组,重新赋予数组新的下标 shuffle($return); return $return; } //生成10个1到100范围内的不重复随机数 $arr = unique_rand(1, 100, 10); echo implode($arr, ","); ?>
The above is the detailed content of How to generate unique numbers in php. For more information, please follow other related articles on the PHP Chinese website!