Summary of 5 Methods of Generating Non repeating Random Numbers in PHP

  • 2021-07-26 07:03:25
  • 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 commonly used in a summary of several methods (ps: methods 1, 4 and 5 are commonly used by me, and the rest come from network collation)

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, most random numbers can be generated from the perspective of arrays, if you have methods to provide, welcome to give, the article will continue to update.


Related articles: