PHP code for generating N non-repeated random numbers

Source: Internet
Author: User

CopyCode The Code is as follows: <? PHP
// Range is an array of columns from 1 to 100.
$ Numbers = range (1, 1,100 );
// Shuffle will immediately disrupt the array order
Shuffle ($ numbers );
// Array_slice retrieves a segment 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 codeThe Code is as follows: // range is to convert columns 1 to 42 into an array.
$ Numbers = range (1, 42 );
// Shuffle will immediately disrupt the array order
Shuffle ($ numbers );
// Array_slice retrieves a segment of the array
$ Result = array_slice ($ numbers, 0, 3 );
Print_r ($ result );

Method 2Copy codeThe Code is as follows: <? PHP
$ Numbers = range (1, 20 );
Srand (float) microtime () * 1000000 );
Shuffle ($ numbers );
While (List (, $ number) = each ($ numbers )){
Echo "$ number ";
}
?>

Method 3
With PHP, 5 non-repeated values are randomly generated between 1 and 20. How can this problem be solved?Copy codeThe Code is as follows: <? PHP
Function norand ($ begin = 0, $ end = 20, $ Limit = 5 ){
$ Rand_array = range ($ begin, $ end );
Shuffle ($ rand_array); // call the random array arrangement function.
Return array_slice ($ rand_array, 0, $ limit); // the first $ limit
}
Print_r (norand ());
?>

or copy Code the code is as follows: $ TMP = array ();
while (count ($ TMP) <5) {
$ TMP [] = mt_rand (1, 20 );
$ TMP = array_unique ($ TMP);
}< br> 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.