PHP: A method for generating non-repeating random numbers

Source: Internet
Author: User

Source: http://www.ido321.com/1217.html

Whether it's a Web application, a WAP, or a mobile app, random numbers have their way. In several recent small projects, I also often need to deal with random numbers or random arrays, so, for PHP how to produce non-repeating random number of common methods to summarize (PS: Methods 1, 4, 5 is what I used, the rest from the network finishing)

Method One:

$num = 6; $result = Array_slice ($numbers, 0, $num); Print_r ($result);?>

Method Two:

//Sow random number generator seed, dispensable, no effect on the result after testing Srand (float//Skip list First value (save index) while (list  echo"$number";}? >

Method Three:

function Norand ($begin =0, $end =20, $limit =5) {$rand _array=range ($begin, $end); Shuffle ($rand _array);  return array_slice ($rand _array,0, $limit);  } print_r (Norand ());?>

The above can randomly produce 5 distinct values in 1-20.

Method Four:

<?php $tmp =arraywhile (count ($tmp) <5) {$tmp []=mt_rand (1,20); $tmp =array_unique ($tmp);} Print_r ($tmp);? >

Method Five:

<?php $tmp = Range (1,30);p Rint_r (Array_rand ($tmp, 10));? >

This may be simpler than the call. (PS: If you specify a step in range, you must be aware that the second parameter of Array_rand exceeds the length of $tmp).

PHP provides a very rich array of functions, the generation of random numbers can be from the angle of the array, if you have a way to provide, welcome, the article will continue to update.

Next: PHP: A method of generating non-repeating random numbers

PHP: A method for generating non-repeating random numbers

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.