PHP: Method for generating random numbers without duplicates. php Method for repeating random numbers
Source: http://www.ido321.com/1217.html
Random numbers are useful for Web applications, WAP or mobile applications. In recent small projects, I often need to deal with random numbers or random arrays. Therefore, I would like to summarize several common methods for generating non-repeated random numbers in PHP (ps: methods 1, 4, and 5 are commonly used, and the rest are from network arrangement)
Method 1:
<? Php $ numbers = range (); // shuffle the array order and then shuffle ($ numbers); // array_slice retrieves a section of the array $ num = 6; $ result = array_slice ($ numbers, 0, $ num); print_r ($ result);?>
Method 2:
<? Php $ numbers = range (1000000); // broadcast the seed of the random number generator, which is dispensable. srand (float) microtime () *) is not affected after the test ); shuffle ($ numbers); // skip the first value of list (the index is saved) while (list (, $ number) = each ($ numbers )) {echo "$ number" ;}?>
Method 3:
<? Php function NoRand ($ begin = 0, $ end = 20, $ limit = 5) {$ rand_array = range ($ begin, $ end); shuffle ($ rand_array ); // call the ready-made random array arrangement function return array_slice ($ rand_array, 0, $ limit); // cut the first $ limit} print_r (NoRand ();?>
Five distinct values can be randomly generated between 1 and 20.
Method 4:
<?php $tmp=array(); while(count($tmp)<5){ $tmp[]=mt_rand(1,20); $tmp=array_unique($tmp); } print_r($tmp);?>
Method 5:
<?php $tmp = range(1,30);print_r(array_rand($tmp,10));?>
This may be simpler (ps: If the step is specified in the range, you must note whether the second parameter of array_rand exceeds the length of $ tmp ).
PHP provides a rich array function, and generates random numbers most of the time from the array perspective. If you have other methods available, please refer to the article for continuous updates.
Next article: PHP: Method for generating random numbers without duplicates