PHP n non-repetitive random number generation code _php tips

Source: Internet
Author: User
Copy Code code as follows:

<?php
Range is to list 1 to 100 as an array
$numbers = range (1,100);
Shuffle the array order immediately
Shuffle ($numbers);
Array_slice a section of the array
$no = 6;
$result = Array_slice ($numbers, 0, $no);
for ($i =0; $i < $no; $i + +) {
echo $result [$i]. " <br> ";
}
Print_r ($result);
?>

Copy Code code as follows:

Range is to list 1 to 42 as an array
$numbers = range (1,42);
Shuffle the array order immediately
Shuffle ($numbers);
Array_slice a section of the array
$result = Array_slice ($numbers, 0, 3);
Print_r ($result);

Method 2
Copy Code code as follows:

<?php
$numbers = range (1,20);
Srand ((float) microtime () *1000000);
Shuffle ($numbers);
while (the list (, $number) = each ($numbers)) {
echo "$number";
}
?>
Method 3
With PHP, in 1-20 randomly generated 5 distinct values, how to do
Copy Code code as follows:

<?php
function Norand ($begin =0, $end =20, $limit =5) {
$rand _array=range ($begin, $end);
Shuffle ($rand _array);//Call ready-made array random order function
Return Array_slice ($rand _array,0, $limit);//$limit before intercept
}
Print_r (Norand ());
?>

Or not shuffle.
Copy Code code as follows:

<?php
$tmp =array ();
while (count ($tmp) <5) {
$tmp []=mt_rand (1,20);
$tmp =array_unique ($tmp);
}
Print join (', ', $tmp);
?>

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.