PHP generates n non-repeating random number instances detailed _php tutorial

Source: Internet
Author: User
I used to give you a talk about generating multiple random numbers, let me introduce an example of PHP generation n non-repeating random numbers, if you are interested, we can refer to.

This is not a difficult task to implement, but I have learned a lot.

copy code

/**

* Generate a certain number of distinct random numbers

* @param int $min, $max Specify the range of random numbers

* @param int $max

* @param int $num Specify the number of builds

* @return Array

*/

Fun Ction Unique_rand ($min, $max, $num) {

$count = 0;

$return = array ();

while ($count < $num) {

$return [] = Mt_rand ($min, $max);

$return = Array_flip (Array_flip ($return));

$count = count ($return);

}

Shuffle ($return);

Return $return;

}

The Mt_rand () function is used when generating random numbers. The average speed of this function generates random numbers four times times faster than Rand ().
Removing duplicate values in the array uses the "rollover" method, which uses Array_flip () to swap the array's key and value two times. This approach is much faster than using Array_unique ().
Before returning an array, use Shuffle () to assign a new key name to the group, guaranteeing that the key name is 0-n consecutive digits. If you do not do this, you may cause the key name to be discontinuous when you delete duplicate values, causing the traversal to be cumbersome.

http://www.bkjia.com/PHPjc/633145.html www.bkjia.com true http://www.bkjia.com/PHPjc/633145.html techarticle I used to give you a talk about generating multiple random numbers, let me introduce an example of PHP generation n non-repeating random numbers, if you are interested, we can refer to. To achieve this ...

  • 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.