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:

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

Method 2:

$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:

function NoRand($begin=0,$end=20,$limit=5){
shuffle($rand_array);// Call the ready-made array random arrangement function
return array_slice($rand_array,0,$limit);// Before interception $limit A

The above can randomly generate 5 non-repeating values between 1 and 20

Method 4:


Method 5:

$tmp = range(1,30);

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: