Home >Backend Development >PHP Tutorial >PHP function: generate N non-repeating random numbers, php random numbers_PHP tutorial
Idea: Store the generated random numbers in an array, and then remove duplicate values from the array to generate a certain number of non-repeating random numbers.
Program:
<?php /* * array unique_rand( int $min, int $max, int $num ) * 生成一定数量的不重复随机数 * $min 和 $max: 指定随机数的范围 * $num: 指定生成数量 */ function unique_rand($min,$max,$num){ $count = 0; $return_arr = array(); while($count < $num){ $return_arr[] = mt_rand($min,$max); $return_arr = array_flip(array_flip($return_arr)); $count = count($return_arr); } shuffle($return_arr); return $return_arr; }
Additional instructions:
1. The mt_rand() function is used to generate random numbers. This function is 4 times faster than the rand() function;
2. When removing duplicate values from an array, the "flip method" is used, which is to use array_flip() to exchange the key and value of the array twice. Much faster than using array_unique().