Home > Article > Backend Development > What are the ways to generate random numbers in PHP?
This time I will bring you some methods of generating random numbers in PHP, and notes on generating random numbers in PHP. The following is a practical case, let's take a look.
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;
Second method (fastest)
function make_password( $length = 8 ) { // 密码字符集,可任意添加你需要的字符 $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', '!', '@','#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '[', ']', '{', '}', '<', '>', '~', '`', '+', '=', ',', '.', ';', ':', '/', '?', '|'); // 在 $chars 中随机取 $length 个数组元素键名 $keys = array_rand($chars, $length); $password = ''; for($i = 0; $i < $length; $i++) { // 将 $length 个数组元素连接成字符串 $password .= $chars[$keys[$i]]; } return $password; }
The third method is to take the current timetime stamp
function get_password( $length = 8 ) { $str = substr(md5(time()), 0, $length);//md5加密,time()当前时间戳 return $str; }
The fourth way to scramble strings
function getrandstr(){ $str='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'; $randStr = str_shuffle($str);//打乱字符串 $rands= substr($randStr,0,6);//substr(string,start,length);返回字符串的一部分 return $rands; }
//Start creating Verification code (generated directly using a function, which is more convenient and fast)
$code = rand(10000, 99999);
Comparison of the effects of php mt_rand generating 0~1 random decimals
lcg_value description
float lcg_value (void)
lcg_value() returns a pseudo-random number in the range (0, 1). This function combines two congruential 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: a pseudo-random number 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 of generating random decimals from 0 to 1
1.Execution time comparison
The running time of executing the algorithm based on mt_rand() and mt_getrandmax() 100,000 times
<?php /** * 生成0~1随机小数 * @param Int $min * @param Int $max * @return Float */ function randFloat($min=0, $max=1){ return $min + mt_rand()/mt_getrandmax() * ($max-$min); } // 获取microtime function get_microtime(){ list($usec, $sec) = explode(' ', microtime()); return (float)$usec + (float)$sec; } // 记录开始时间 $starttime = get_microtime(); // 执行10万次获取随机小数 for($i=0; $i<100000; $i++){ randFloat(); } // 记录结束时间 $endtime = get_microtime(); // 输出运行时间 printf("run time %f ms\r\n", ($endtime-$starttime)*1000); ?>
Output: run time 266.893148 ms
Running time of executing lcg_value() 100,000 times
<?php // 获取microtime function get_microtime(){ list($usec, $sec) = explode(' ', microtime()); return (float)$usec + (float)$sec; } // 记录开始时间 $starttime = get_microtime(); // 执行10万次获取随机小数 for($i=0; $i<100000; $i++){ lcg_value(); } // 记录结束时间 $endtime = get_microtime(); // 输出运行时间 printf("run time %f ms\r\n", ($endtime-$starttime)*1000); ?>
Output: run time 86.178064 ms
Comparison of execution time, because lcg_value() is directly a native PHP method, while mt_rand() and mt_getrandmax() need to call two methods and need to be calculated, so the execution time of lcg_value() is about 3 times faster.
2. Comparison of random effects
Random effect based on mt_rand() and mt_getrandmax() algorithms
<?php /** * 生成0~1随机小数 * @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); ?>
The random effect 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); ?>
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
How to install third-party libraries in anaconda in win
The above is the detailed content of What are the ways to generate random numbers in PHP?. For more information, please follow other related articles on the PHP Chinese website!