PHP生成随机数的方法总结

本篇文章给大家总结了PHP生成随机数的方法并把相关的代码做了分享,有需要的读者们参考学习下吧。

第一种方法用mt_rand()

  1. function GetRandStr($length){
  2. $str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  3. $len=strlen($str)-1;
  4. $randstr='';
  5. for($i=0;$i<$length;$i++){
  6. $num=mt_rand(0,$len);
  7. $randstr .= $str[$num];
  8. }
  9. return $randstr;
  10. }
  11. $number=GetRandStr(6);
  12. echo $number;

第二种方法(最快的)

  1. function make_password( $length = 8 )
  2. {
  3. // 密码字符集,可任意添加你需要的字符
  4. $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
  5. 'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's',
  6. 't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D',
  7. 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O',
  8. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z',
  9. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!',
  10. '@','#', '$', '%', '^', '&', '*', '(', ')', '-', '_',
  11. '[', ']', '{', '}', '<', '>', '~', '`', '+', '=', ',',
  12. '.', ';', ':', '/', '?', '|');
  13. // 在 $chars 中随机取 $length 个数组元素键名
  14. $keys = array_rand($chars, $length);
  15. $password = '';
  16. for($i = 0; $i < $length; $i++)
  17. {
  18. // 将 $length 个数组元素连接成字符串
  19. $password .= $chars[$keys[$i]];
  20. }
  21. return $password;
  22. }

第三种取当时时间戳

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

第四种打乱字符串

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

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

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

  1. <?php
  2. for($i=0; $i<5; $i++){
  3. echo lcg_value().PHP_EOL;
  4. }
  5. ?>

输出:

  1. 0.11516515851995
  2. 0.064684551575297
  3. 0.68275174031189
  4. 0.55730746529099
  5. 0.70215008878091

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

1.执行时间比较

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

  1. <?php
  2. /**
  3. * 生成0~1随机小数
  4. * @param Int $min
  5. * @param Int $max
  6. * @return Float
  7. */
  8. function randFloat($min=0, $max=1){
  9. return $min + mt_rand()/mt_getrandmax() * ($max-$min);
  10. }
  11. // 获取microtime
  12. function get_microtime(){
  13. list($usec, $sec) = explode(' ', microtime());
  14. return (float)$usec + (float)$sec;
  15. }
  16. // 记录开始时间
  17. $starttime = get_microtime();
  18. // 执行10万次获取随机小数
  19. for($i=0; $i<100000; $i++){
  20. randFloat();
  21. }
  22. // 记录结束时间
  23. $endtime = get_microtime();
  24. // 输出运行时间
  25. printf("run time %f ms\r\n", ($endtime-$starttime)*1000);
  26. ?>

输出:run time 266.893148 ms

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

  1. <?php
  2. // 获取microtime
  3. function get_microtime(){
  4. list($usec, $sec) = explode(' ', microtime());
  5. return (float)$usec + (float)$sec;
  6. }
  7. // 记录开始时间
  8. $starttime = get_microtime();
  9. // 执行10万次获取随机小数
  10. for($i=0; $i<100000; $i++){
  11. lcg_value();
  12. }
  13. // 记录结束时间
  14. $endtime = get_microtime();
  15. // 输出运行时间
  16. printf("run time %f ms\r\n", ($endtime-$starttime)*1000);
  17. ?>

输出:run time 86.178064 ms

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

2.随机效果比较

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

  1. <?php
  2. /**
  3. * 生成0~1随机小数
  4. * @param Int $min
  5. * @param Int $max
  6. * @return Float
  7. */
  8. function randFloat($min=0, $max=1){
  9. return $min + mt_rand()/mt_getrandmax() * ($max-$min);
  10. }
  11. header('content-type: image/png');
  12. $im = imagecreatetruecolor(512, 512);
  13. $color1 = imagecolorallocate($im, 255, 255, 255);
  14. $color2 = imagecolorallocate($im, 0, 0, 0);
  15. for($y=0; $y<512; $y++){
  16. for($x=0; $x<512; $x++){
  17. $rand = randFloat();
  18. if(round($rand,2)>=0.5){
  19. imagesetpixel($im, $x, $y, $color1);
  20. }else{
  21. imagesetpixel($im, $x, $y, $color2);
  22. }
  23. }
  24. }
  25. imagepng($im);
  26. imagedestroy($im);
  27. ?>

lcg_value()的随机效果

  1. <?php
  2. header('content-type: image/png');
  3. $im = imagecreatetruecolor(512, 512);
  4. $color1 = imagecolorallocate($im, 255, 255, 255);
  5. $color2 = imagecolorallocate($im, 0, 0, 0);
  6. for($y=0; $y<512; $y++){
  7. for($x=0; $x<512; $x++){
  8. $rand = lcg_value();
  9. if(round($rand,2)>=0.5){
  10. imagesetpixel($im, $x, $y, $color1);
  11. }else{
  12. imagesetpixel($im, $x, $y, $color2);
  13. }
  14. }
  15. }
  16. imagepng($im);
  17. imagedestroy($im);
  18. ?>