您现在的位置是:首页 > 学无止境 > PHPPHP

PHP中生成随机数有哪些方法

AndyGuo2020-07-15 12:07:12PHP1342人已围观

简介生成随机数是我们经常要要用到的,今天小郭就给大伙说道说道

生成随机数是我们经常要要用到的,今天小郭就给大伙说道说道。

第一种方法用mt_rand()

第二种方法(最快的)

第三种取当时时间戳

第四种打乱字符串

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

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

1.执行时间比较

2.随机效果比较

3.随机阅读推荐

一、用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);


小郭博客

相关文章

标签云 更多

关闭
QQ 微信 支付宝扫一扫打赏