**php Random number algorithm

Source: Internet
Author: User

<?php
$tmp = range (1,30);
Print_r (Array_rand ($tmp, 10));
?>

Output:

Array
(
[0] = 6
[1] = 8
[2] = 13
[3] = 16
[4] = 17
[5] = 20
[6] = 21
[7] = 22
[8] = 28
[9] = 29
)

-----------------------------------------

Reference:

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 CodeThe code is 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 CodeThe code is 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 CodeThe code is 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 CodeThe code is as follows:
<?php
$tmp =array ();
while (count ($tmp) <5) {
$tmp []=mt_rand (1,20);
$tmp =array_unique ($tmp);
}
Print_r ($TMP);
?>

Method Five:

Copy CodeThe code is as follows:
<?php
$tmp = range (1,30);
Print_r (Array_rand ($tmp, 10));
?>

**php Random number algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.