This article focuses on how to use PHP to generate n non-repeating random number instances , the code is as follows:
<?php/** array Unique_rand (int $min, int $max, int $num) * Generates a certain number of distinct random numbers * $min and $max: Specify the range of random numbers * $num: Specify the number of builds */functio N 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;} $arr = Unique_rand (1, +), sort ($arr), $result = ", for ($i =0; $i < count ($arr); $i + +) {$result. = $arr [$i]. ', ';} $result = substr ($result, 0,-1); Echo $result;? >
The program runs as follows:
The code is as follows:
2,3,4,6,7,8,9,10,11,12,13,16,20,21,22,24
The
Adds several notes:
the Mt_rand () function is used when generating random numbers. The average speed of this function generates random numbers four times times faster than Rand (). The
"rollover" is used to remove duplicate values from the array, which is to exchange the key and value of the array two times with Array_flip (). This approach is much faster than using Array_unique ().
before returning an array, use shuffle () to give the new key name to the group, guaranteeing that the key name is 0-n consecutive numbers. If you do not do this, you may cause the key name to be discontinuous when you delete duplicate values, causing the traversal to be cumbersome.