Summary of Methods of Generating Random Numbers in PHP
- 2021-09-12 00:35:23
- OfStack
The first method uses mt_rand ()
function GetRandStr($length){
$str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$len=strlen($str)-1;
$randstr='';
for($i=0;$i<$length;$i++){
$num=mt_rand(0,$len);
$randstr .= $str[$num];
}
return $randstr;
}
$number=GetRandStr(6);
echo $number;
Method 2 (Fastest)
function make_password( $length = 8 )
{
// Password character set, you can add any characters you need
$chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!',
'@','#', '$', '%', '^', '&', '*', '(', ')', '-', '_',
'[', ']', '{', '}', '<', '>', '~', '`', '+', '=', ',',
'.', ';', ':', '/', '?', '|');
// In $chars Random selection in $length Array element key names
$keys = array_rand($chars, $length);
$password = '';
for($i = 0; $i < $length; $i++)
{
// Will $length Array elements are concatenated into strings
$password .= $chars[$keys[$i]];
}
return $password;
}
The third is to take the time stamp at that time
function get_password( $length = 8 )
{
$str = substr(md5(time()), 0, $length);//md5 Encryption, time() Current timestamp
return $str;
}
The fourth scrambling string
function getrandstr(){
$str='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
$randStr = str_shuffle($str);// Scramble a string
$rands= substr($randStr,0,6);//substr(string,start,length); Returns the of the string 1 Part
return $rands;
}
//Start creating verification code (directly generated by function, which is more convenient and quick)
$code = rand(10000, 99999);
Comparison of the effects of php mt_rand on generating 0 ~ 1 random decimals
lcg_value Description
float lcg_value ( void )
lcg_value () returns a pseudo-random number with a range of (0, 1). This function combines two congruence generators with periods 2 ^ 31-85 and 2 ^ 31-249. The period of this function is equal to the product of these two prime numbers.
Returns: Pseudorandom numbers in the range (0, 1).
<?php
for($i=0; $i<5; $i++){
echo lcg_value().PHP_EOL;
}
?>
Output:
0.11516515851995
0.064684551575297
0.68275174031189
0.55730746529099
0.70215008878091
Comparison of two methods for generating 0 ~ 1 random decimals
1. Execution time comparison
Runtime to execute 100,000 times based on mt_rand () and mt_getrandmax () algorithms
<?php
/**
* Generate 0~1 Random decimal
* @param Int $min
* @param Int $max
* @return Float
*/
function randFloat($min=0, $max=1){
return $min + mt_rand()/mt_getrandmax() * ($max-$min);
}
// Get microtime
function get_microtime(){
list($usec, $sec) = explode(' ', microtime());
return (float)$usec + (float)$sec;
}
// Record start time
$starttime = get_microtime();
// Execute 10 Get random decimals ten thousand times
for($i=0; $i<100000; $i++){
randFloat();
}
// Record end time
$endtime = get_microtime();
// Output runtime
printf("run time %f ms\r\n", ($endtime-$starttime)*1000);
?>
Output: run time 266.893148 ms
Run time of executing lcg_value () 100,000 times
<?php
// Get microtime
function get_microtime(){
list($usec, $sec) = explode(' ', microtime());
return (float)$usec + (float)$sec;
}
// Record start time
$starttime = get_microtime();
// Execute 10 Get random decimals ten thousand times
for($i=0; $i<100000; $i++){
lcg_value();
}
// Record end time
$endtime = get_microtime();
// Output runtime
printf("run time %f ms\r\n", ($endtime-$starttime)*1000);
?>
Output: run time 86.178064 ms
Because lcg_value () is directly the native method of php, and mt_rand () and mt_getrandmax () need to call two methods and need to be evaluated, the execution time of lcg_value () is about three times faster.
2. Random effect comparison
Random Effects Based on mt_rand () and mt_getrandmax () Algorithms
<?php
/**
* Generate 0~1 Random decimal
* @param Int $min
* @param Int $max
* @return Float
*/
function randFloat($min=0, $max=1){
return $min + mt_rand()/mt_getrandmax() * ($max-$min);
}
header('content-type: image/png');
$im = imagecreatetruecolor(512, 512);
$color1 = imagecolorallocate($im, 255, 255, 255);
$color2 = imagecolorallocate($im, 0, 0, 0);
for($y=0; $y<512; $y++){
for($x=0; $x<512; $x++){
$rand = randFloat();
if(round($rand,2)>=0.5){
imagesetpixel($im, $x, $y, $color1);
}else{
imagesetpixel($im, $x, $y, $color2);
}
}
}
imagepng($im);
imagedestroy($im);
?>
Random effects of lcg_value ()
<?php
header('content-type: image/png');
$im = imagecreatetruecolor(512, 512);
$color1 = imagecolorallocate($im, 255, 255, 255);
$color2 = imagecolorallocate($im, 0, 0, 0);
for($y=0; $y<512; $y++){
for($x=0; $x<512; $x++){
$rand = lcg_value();
if(round($rand,2)>=0.5){
imagesetpixel($im, $x, $y, $color1);
}else{
imagesetpixel($im, $x, $y, $color2);
}
}
}
imagepng($im);
imagedestroy($im);
?>