I have told you about generating multiple random numbers before. Now I will introduce an example of generating N non-repeating random numbers in PHP. If you are interested, you can refer to it.
It is not difficult to implement this function, but it made me learn a lot.
The code is as follows
代码如下 |
复制代码 |
/**
* 生成一定数量的不重复随机数
* @param int $min ,$max指定随机数的范围
* @param int $max
* @param int $num 指定生成数量
* @return array
*/
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;
}
|
|
Copy code
|
/**
| * Generate a certain number of unique random numbers
* @param int $min, $max specifies the range of random numbers
* @param int $max
* @param int $num specifies the number of generated
* @return array
*/
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;
}
The mt_rand() function is used to generate random numbers. This function generates random numbers four times faster on average than rand().
The "flip method" is used to remove duplicate values in the array, which is to use array_flip() to exchange the key and value of the array twice. This approach is much faster than using array_unique().
Before returning the array, first use shuffle() to assign new key names to the array, ensuring that the key names are consecutive numbers from 0-n. If this step is not performed, key names may become discontinuous when deleting duplicate values, causing trouble in traversal.
http://www.bkjia.com/PHPjc/633145.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/633145.htmlTechArticleI have told you about generating multiple random numbers before. Now I will introduce another article about generating N random numbers in PHP. Examples of non-repeating random numbers. If you are interested, you can refer to it. To achieve this...