Generate multiple non-repeating random numbers PHP

Source: Internet
Author: User

This is no good nonsense;

The first is to use the Mt_rand () function to generate a specified number of random numbers;

Then use the Array_unique () function to go heavy;

Because go heavy, so get the number is not enough to specify the number of;

So, the core is to use the while loop, until the number of the specified number is obtained;

The basic can be the end here;

For the perfect person, you can also use a sort ();

The purpose is not to be used for sorting; The key is to format the resulting array key;

To speak in code, as follows;

/**
* Generate non-repeating random numbers
* @param int $start The number start range that needs to be generated
* @param int $end End Range
* @param int $length The number of random numbers that need to be generated
* @return random number generated by array
*/
function Get_rand_number ($start =1, $end =10, $length =4) {
$connt = 0;
$temp =array ();
while ($connt < $length) {
$temp []=mt_rand ($start, $end);
$data =array_unique ($temp);
$connt =count ($data);
}
Sort ($data);
return $data;
}

Of course, the emphasis is not on this function; The emphasis is on the idea of this function; it can solve many similar problems;

Generate multiple non-repeating random numbers PHP

Related Article

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.