This paper summarizes 5 kinds of methods of generating non-repeating random numbers, of which methods one or two and three are my usual methods, and the method Siburai to degree Niang. The rest of the methods are still there, we also welcome the omission of the method of reporting, we progress together
Whether it's a Web application, a WAP, or a mobile app, random numbers have their way. I also often need to deal with random numbers or random arrays in several small projects that I have recently contacted, so there are a few ways to summarize how PHP produces non-repeating random numbers.
Method One:
Copy the Code code as follows:
<?php
$numbers = range (1,50);
Shuffle the array order is scrambled
Shuffle ($numbers);
Array_slice take a segment of the array
$num = 6;
$result = Array_slice ($numbers, 0, $num);
Print_r ($result);
?>
Method Two:
Copy the Code code as follows:
<?php
$numbers = range (1,20);
Sowing random number generator seeds, optional, no effect on the results after testing
Srand (float) microtime () *1000000);
Shuffle ($numbers);
Skip list First value (save index)
while (list (, $number) = each ($numbers)) {
echo "$number";
}
?>
Method Three:
Copy the Code code as follows:
<?php
function Norand ($begin =0, $end =20, $limit =5) {
$rand _array=range ($begin, $end);
Shuffle ($rand _array);//Call out-of-box array random permutation function
Return Array_slice ($rand _array,0, $limit);//$limit before intercept
}
Print_r (Norand ());
?>
The above can randomly produce 5 distinct values in 1-20.
Method Four:
Copy the Code code as follows:
<?php
$tmp =array ();
while (count ($tmp) <5) {
$tmp []=mt_rand (1,20);
$tmp =array_unique ($tmp);
}
Print_r ($TMP);
?>
Method Five:
Copy the Code code as follows:
<?php
$tmp = range (1,30);
Print_r (Array_rand ($tmp, 10));
?>
This may be simpler than the call. (PS: If you specify a step in range, you must be aware that the second parameter of Array_rand exceeds the length of $tmp).
PHP provides a very rich array of functions, the generation of random numbers can be mostly from the angle of the array, of course, if you have a better method, please also tell, this article is also a point of view.
Articles you may be interested in:
Red envelope random generation algorithm PHP version
Randomly generated red envelope amount algorithm PHP version
jquery+php randomly generated red envelopes amount number code share
PHP probabilistic algorithm for lottery programs and random ads
An algorithm for efficiently and randomly extracting specified bar records from an array in PHP
Three ways to generate random numbers in PHP
PHP n Non-repeating random number generation code
PHP generates random strings (3 methods)
PHP Random string generation code (including uppercase and lowercase letters)
A method of randomly generating alphanumeric combinations in PHP
Example of random red envelope algorithm implemented by PHP