This time to bring you PHP to generate custom length random string steps, the PHP generation of custom-length random string considerations are what, the following is the actual case, take a look.
Randomly generated string function random ($length) { Srand (date ("S")); $possible _charactors = "0123456789abcdefghijklmnopqrstuvwxyz"; $string = ""; while (strlen ($string) < $length) { $string. = substr ($possible _charactors, (rand ()% (Strlen ($possible _ charactors))), 1); } return ($string);}
Example 2,php generating n non-repeating random number instances
Using PHP to generate an instance method of n non-repeating random numbers
There are 25 pieces to vote, one to vote for 16, and one to vote only once per piece.
In front of a programmer stabbed blunder, forgot to put the vote in the library, there are 200 user-generated voting sequence is empty. So how would you fill this blunder?
Need to generate 16 non-repeating random numbers between 1-25 to fill. How do you design the function specifically? A certain number of distinct random numbers can be generated by storing random numbers in an array and then removing duplicate values in the array.
Program:
<?php/** array Unique_rand (int $min, int $max, int $num) * Generates a certain number of distinct random numbers * $min and $max: Specify the range of random numbers * $num: Specify the number of builds/WWW.JB Xue.comfunction 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;} $arr = Unique_rand (1, +), sort ($arr), $result = ", for ($i =0; $i < count ($arr); $i + +) {$result. = $arr [$i]. ', ';} $result = substr ($result, 0,-1); Echo $result;? >
Program run:
2,3,4,6,7,8,9,10,11,12,13,16,20,21,22,24
Add:
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.
Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!
Recommended reading:
PHP Zip Compression class instance steps in detail
PHP Judgment program running State step