PHP生成随机数的方法总结

第一种方法用mt_rand()

rush:PHP;"> 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;

第二种方法(最快的)

rush:PHP;"> 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; }

第三种取当时时间戳

rush:PHP;"> function get_password( $length = 8 ) { $str = substr(md5(time()),$length);//md5加密,time()当前时间戳 return $str; }

第四种打乱字符串

rush:PHP;"> function getrandstr(){ $str='ABCDEFGHIJKLMnopQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'; $randStr = str_shuffle($str);//打乱字符串 $rands= substr($randStr,6);//substr(string,start,length);返回字符串的一部分 return $rands; }

//开始创建验证码(直接用函数生成,比较方便快捷)

rush:PHP;"> $code = rand(10000,99999);

PHP mt_rand生成0~1随机小数的效果比较

lcg_value说明

float lcg_value ( void )

lcg_value() 返回范围为 (0,1) 的一个随机数。本函数组合了周期为 2^31 - 85 和 2^31 - 249 的两个同余发生器。本函数的周期等于这两个素数的乘积。

返回:范围为 (0,1) 的伪随机数。

rush:PHP;"> PHP for($i=0; $i<5; $i++){ echo lcg_value().PHP_EOL; } ?>

输出

0.11516515851995 0.064684551575297 0.68275174031189 0.55730746529099 0.70215008878091

两种生成0~1随机小数方法进行比较

1.执行时间比较

执行10万次基于mt_rand()与mt_getrandmax()算法的运行时间

rush:PHP;"> 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);
?>

输出:run time 266.893148 ms

执行10万次lcg_value()的运行时间

rush:PHP;"> PHP // 获取microtime function get_microtime(){ list($usec,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);
?>

输出:run time 86.178064 ms

执行时间上比较,因为lcg_value()直接是PHP原生方法,而mt_rand()与mt_getrandmax()需要调用两个方法,并需要进行计算,因此lcg_value()的执行时间大约快3倍。

2.随机效果比较

基于mt_rand()与mt_getrandmax()算法的随机效果

rush:PHP;"> 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);
$color2 = imagecolorallocate($im,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,$color2);
}
}
}
imagepng($im);
imagedestroy($im);
?>

lcg_value()的随机效果

rush:PHP;"> PHP header('content-type: image/png'); $im = imagecreatetruecolor(512,0); for($y=0; $y<512; $y++){ for($x=0; $x<512; $x++){ $rand = lcg_value(); if(round($rand,$color2); } } } imagepng($im); imagedestroy($im); ?>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


服务器优化必备:深入了解PHP8底层开发原理
Golang的网络编程:如何快速构建高性能的网络应用?
Golang和其他编程语言的对比:为什么它的开发效率更高?
PHP8底层开发原理揭秘:如何利用新特性创建出色的Web应用
将字符重新排列以形成回文(如果可能)在C++中
掌握PHP8底层开发原理和新特性:创建高效可扩展的应用程序
服务器性能优化必学:掌握PHP8底层开发原理
PHP8新特性和底层开发原理详解:优化应用性能的终极指南
将 C/C++ 代码转换为汇编语言
深入研究PHP8底层开发原理:创建高效可扩展的应用程序
C++程序查找法向量和迹
PHP8底层开发原理实战指南:提升服务器效能
重排数组,使得当 i 为偶数时,arr[i] >= arr[j],当 i 为奇数时,arr[i] <= arr[j],其中 j < i,使用 C++ 语言实现
Golang的垃圾回收:为什么它可以减少开发人员的负担?
C++程序:将一个数组的所有元素复制到另一个数组中
Golang:构建智能系统的基石
为什么AI开发者应该关注Golang?
在C和C++中,逗号(comma)的用法是用来分隔表达式或语句
PHP8底层开发原理解析及新特性应用实例
利用PHP8底层开发原理解析新特性:如何构建出色的Web应用