PHP生成随机数的方法总结


Posted in PHP onMarch 01, 2018

第一种方法用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;

第二种方法(最快的)

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; 
}

第三种取当时时间戳

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

第四种打乱字符串

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

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

$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) 的伪随机数。

<?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()算法的运行时间

<?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()的运行时间

<?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);
?>

输出:run time 86.178064 ms

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

2.随机效果比较

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

<?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);
?>

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);
?>
PHP 相关文章推荐
PHP脚本的10个技巧(7)
Oct 09 PHP
PHP的变量总结 新手推荐
Apr 18 PHP
ThinkPHP实现批量删除数据的代码实例
Jul 02 PHP
PHP编程中的常见漏洞和代码实例
Aug 06 PHP
PHP+jQuery 注册模块的改进(一):验证码存入SESSION
Oct 14 PHP
PHP实现UTF-8文件BOM自动检测与移除实例
Nov 05 PHP
PHP缓存集成库phpFastCache用法
Dec 15 PHP
PHP中实现Bloom Filter算法
Mar 30 PHP
Yii基于数组和对象的Model查询技巧实例详解
Dec 28 PHP
thinkPHP使用pclzip打包备份mysql数据库的方法
Apr 30 PHP
php中mkdir()函数的权限问题分析
Sep 24 PHP
PHP类相关知识点实例总结
Sep 28 PHP
PHP Post获取不到非表单数据的问题解决办法
Feb 27 #PHP
php实现生成带二维码图片并强制下载功能
Feb 24 #PHP
php递归函数怎么用才有效
Feb 24 #PHP
php格式文件打开的四种方法
Feb 24 #PHP
Docker搭建自己的PHP开发环境
Feb 24 #PHP
php爬取天猫和淘宝商品数据
Feb 23 #PHP
Laravel如何使用Redis共享Session
Feb 23 #PHP
You might like
《魔兽争霸3:重制版》翻车了?你想要的我们都没有
2019/11/07 魔兽争霸
如何把php5.3版本升级到php5.4或者php5.5
2015/07/31 PHP
PHP验证码生成原理和实现
2016/01/24 PHP
php通过PHPExcel导入Excel表格到MySQL数据库的简单实例
2016/10/29 PHP
Mootools 1.2 手风琴(Accordion)教程
2009/09/15 Javascript
jQuery Validation实例代码 让验证变得如此容易
2010/10/18 Javascript
JavaScript中的变量声明早于赋值分析
2012/03/01 Javascript
js不完美解决click和dblclick事件冲突问题
2012/07/16 Javascript
js+css实现tab菜单切换效果的方法
2015/01/20 Javascript
jquery简单实现网页层的展开与收缩效果
2015/08/07 Javascript
freemarker判断对象是否为空的方法
2015/08/13 Javascript
Vue.js bootstrap前端实现分页和排序
2017/03/10 Javascript
基于JavaScript实现验证码功能
2017/04/01 Javascript
Mint UI组件库CheckList使用及踩坑总结
2018/12/20 Javascript
Vue中使用create-keyframe-animation与动画钩子完成复杂动画
2019/04/09 Javascript
解决vue bus.$emit触发第一次$on监听不到问题
2020/07/28 Javascript
Vue性能优化的方法
2020/07/30 Javascript
vue 保留两位小数 不能直接用toFixed(2) 的解决
2020/08/07 Javascript
vue使用vant中的checkbox实现全选功能
2020/11/17 Vue.js
python 正则式使用心得
2009/05/07 Python
Python爬虫实例爬取网站搞笑段子
2017/11/08 Python
caffe binaryproto 与 npy相互转换的实例讲解
2018/07/09 Python
python 2.7.13 安装配置方法图文教程
2018/09/18 Python
Python实现二叉树前序、中序、后序及层次遍历示例代码
2019/05/18 Python
python 多线程对post请求服务器测试并发的方法
2019/06/13 Python
django 快速启动数据库客户端程序的方法示例
2019/08/16 Python
解决pycharm启动后总是不停的updating indices...indexing的问题
2019/11/27 Python
Python 将 QQ 好友头像生成祝福语的实现代码
2020/05/03 Python
Python小白垃圾回收机制入门
2020/06/09 Python
香港万宁官方海外旗舰店:香港健与美连锁店
2018/09/27 全球购物
食品厂厂长岗位职责
2014/01/30 职场文书
音乐教育专业自荐信
2014/09/18 职场文书
2015大学生实训报告
2014/11/05 职场文书
离职感谢信
2015/01/21 职场文书
2015廉洁自律个人总结
2015/02/14 职场文书
Python还能这么玩之只用30行代码从excel提取个人值班表
2021/06/05 Python