Program to randomly generate a set of non-repeating numbers in PHP_PHP Tutorial
WBOYOriginal
2016-07-13 16:56:461050browse
The following is an introduction to two program codes for randomly generating a set of non-repeating numbers in PHP. Friends who need to learn can refer to them.
// 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,115975
0.672761As you can see from the above results, the time spent is 0.6. Let’s adjust the random number range from 700000 to 900000 and look at the execution resultsFatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 7200000 bytes) in /data0/htdocs/www/a.php on line 10The array is too big and the program cannot run! !
The code is as follows
Copy code
/**
* PHP gets a set of random numbers without repetition
* Qiongtai Blog
* Qiongtai Blog <🎜>
*/<🎜>
$a = microtime(); <🎜>
function createRandID($m){ <🎜>
// Note, you must first declare an empty array, otherwise in_array in while will report an error <🎜>
$arr = array(); <🎜>
// Use a while loop, as long as there are less than 10, it will loop forever <🎜>
While(count($arr)<=10){ <🎜>
// Generate a random number <🎜>
$a = rand(1,$m); <🎜>
// Judgment: If the generated random number is no longer in the array, assign it to the array <🎜>
// Mainly to avoid duplicate numbers <🎜>
If(!in_array($a,$arr)){ <🎜>
//Assign random numbers to the array <🎜>
$arr[] = $a;
} <🎜>
} <🎜>
// Return the generated random number <🎜>
Return implode($arr,','); <🎜>
} <🎜>
echo createRandID(700000); <🎜>
echo ' ';
echo $a - microtime();
?>
Execution result:
308326,155128,280424,493174,214855,219990,482837,66329,512934,232527,386975
0.00015699999999996
As can be seen from the above execution results, the time can be ignored at all. Let’s adjust the random number range from 700000 to 999999 and take a look at the execution results
392281,822956,401282,176255,143076,501802,393338,546922,21836,601991,362006
0.00013600000000002
The execution result has nothing to do with the maximum value setting, it still runs very fast!
http://www.bkjia.com/PHPjc/631573.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631573.htmlTechArticleThe following is an introduction to two program codes for randomly generating a set of non-repeating numbers in PHP. Friends who need to learn Can be used for reference. The code is as follows Copy code ?php /** * PHP gets a set of random...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn