PHP Summary of Methods for Generating Non repeating Random Numbers

  • 2021-08-05 09:10:24
  • OfStack

Whether it is Web application, WAP or mobile application, random numbers have their applications. In the recent contact with several small projects, I often need to deal with random numbers or random arrays, so for PHP how to generate non-repeating random numbers, several commonly used methods are summarized in 1.

Method 1:


<?php
$numbers = range (1,50);
//shuffle Scramble the array order immediately
shuffle ($numbers);
//array_slice Fetches a certain in the array 1 Segment
$num=6;
$result = array_slice($numbers,0,$num);
print_r($result);
?>

Method 2:


<?php
$numbers = range (1,20);
// Sow the seeds of random number generator, optional, and have no effect on the results after testing
srand ((float)microtime()*1000000);
shuffle ($numbers);
// Skip list No. 1 1 Values (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 array random arrangement function
return array_slice($rand_array,0,$limit);// Before interception $limit A
}
print_r(NoRand());
?>

The above can randomly generate 5 non-repeating values 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 than it is called (ps: If you specify a step size in range, you must pay attention to whether the second parameter of array_rand exceeds the length of $tmp).

PHP provides a very rich array function, and most of the random numbers can be generated from the perspective of arrays. Of course, if you have a better method, please tell me. This article is also a good example.


Related articles: