This is nothing to talk about; let’s go straight to the topic and let’s talk about the idea;
The first thing is to use the mt_rand() function to generate a specified number of random numbers;
Then use the array_unique() function to remove duplicates; (Recommended learning: PHP programming from entry to proficiency)
Because of duplicate removal ; so the number obtained is not enough for the specified number;
So, The core is to use a while loop; until the specified number of numbers is obtained;
Go here It can basically be over;
For those who pursue perfection; you can also use sort();
The purpose is not to use for sorting; the main purpose is to format the obtained array key Change;
Let’s talk in code; as follows;
/** * 生成不重复的随机数 * @param int $start 需要生成的数字开始范围 * @param int $end 结束范围 * @param int $length 需要生成的随机数个数 * @return array 生成的随机数 */ function get_rand_number($start=1,$end=10,$length=4){ $connt=0; $temp=array(); while($connt<$length){ $temp[]=mt_rand($start,$end); $data=array_unique($temp); $connt=count($data); } sort($data); return $data; }
The above is the detailed content of How to generate non-repeating random numbers in php. For more information, please follow other related articles on the PHP Chinese website!