Method for generating non-repeated random numbers in PHP

Source: Internet
Author: User

The principle is very simple. First, write a function to generate one of the 36 characters 0-Z. Each time you call the getOptions () method to generate a character, they are stored as follows: array [0] = 0, array [1] = 1 ,......, Array [35] = z.

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => a [11] => b [12] => c [13] => d [14] => e [15] => f [16] => g [17] => h [18] => i [19] => j [20] => k [21] => l [22] => m [23] => n [24] => o [25] => p [26] => q [27] => r [28] => s [29] => t [30] => u [31] => v [32] => w [33] => x [34] => y [35] => z )

Then a random number is generated between 0 and 35 as the index. In fact, a random number is taken out of the above array as the first character in the variable $ result. This Random Index will be assigned to the last one of the array and will not participate in the next round of random selection.

<? Php // generate a character function getOptions () {$ options = array (); $ result = array (); for ($ I = 48; $ I <= 57; $ I ++) {array_push ($ options, chr ($ I) ;}for ($ I = 65; $ I <= 90; $ I ++) {$ j = 32; $ small = $ I + $ j; array_push ($ options, chr ($ small);} return $ options ;} /* $ e = getOptions (); for ($ j = 0; $ j <150; $ j ++) {echo $ e [$ j];} */$ len = 10; // randomly generate an array index to achieve a random number for ($ j = 0; $ j <100; $ j ++) {$ result =" "; $ Options = getOptions (); $ lastIndex = 35; while (strlen ($ result) <$ len) {// randomly retrieve an index from 0 to 35 $ index = rand (0, $ lastIndex ); // assign the random number to the variable $ chr = $ options [$ index]; // the random number is used as part of $ result. = $ chr; $ lastIndex = $ lastIndex-1; // The last index will not participate in the next random lottery $ options [$ index] = $ options [$ lastIndex];} echo $ result. "n" ;}?>

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.