Randomly generated numbers are often applied to random passwords or random verification codes. PHP has the rand () interference function and MD5 function. let's take a look at the combination of PHP functions to generate a set of unique
Randomly generated numbers are often applied to random passwords or random verification codes. PHP uses the rand () interference function and MD5 to implement this, next, let's take a look at how to use a program to generate a set of non-repeated numeric arrays using PHP functions, and directly use the code:
-
-
- /**
- * PHP obtains a set of random numbers without duplicates.
- */
- $ A = microtime ();
- Function createRandID ($ m ){
- // Generate an array from 1 to $ m
- $ Arr = range (1, $ m );
- // Disrupt the array
- Shuffle ($ arr );
- // Obtain the first 10
- For ($ I = 0; $ I <= 10; $ I ++ ){
- // Assign a value to the new array $ n
- $ N [] = $ arr [$ I];
- }
- // Return this set of numbers
- Return implode ($ n ,',');
- }
- Echo createRandID (700000 );
- Echo' ';
- Echo $ a-microtime ();
- ?>
Execution result:
560875,593409, 325987,658308, 248054,205426, 375413,676243, 485853,575393, 1159750.672761
From the above results, we can see that it took 0.6 seconds to adjust the random number range from 700000 to 900000. then we can see the execution result: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 7200000 bytes) in/data0/htdocs/www/. php on line 10
The code is as follows:
-
- /**
- * PHP obtains a set of random numbers without duplicates.
- * PHP blog
- */
- $ A = microtime ();
- Function createRandID ($ m ){
- // Note: you must declare an empty array first. Otherwise, the in_array in while will report an error.
- $ Arr = array ();
- // Use the while loop. if there are less than 10, the loop will always be done.
- While (count ($ arr) <= 10 ){
- // Generate a random number
- $ A = rand (1, $ m );
- // Judgment: If the generated random number is no longer in the array, it is assigned to the array.
- // Avoid repeated numbers
- If (! In_array ($ a, $ arr )){
- // Assign a random number to an array
- $ Arr [] = $;
- }
- }
- // Return the generated random number
- Return implode ($ arr ,',');
- }
- Echo createRandID (700000 );
- Echo' ';
- Echo $ a-microtime ();
- ?>
Execution result:
308326,155128, 280369,493174, 214855,219990, 482837,66329, 512934,232527, 3869750.00015699999999996
We can see from the preceding execution results that the time is negligible. we can adjust the random number range from 700000 to 999999 to see the execution result.
392281,822956, 401282,176255, 143076,501802, 393338,546922, 21836,601991, 3620060.00013600000000002
The execution result has nothing to do with the maximum value setting. it is still running fast!