如何高效率的写一个不会重复出现的随机数

  1. function unique_rand($min,$max,$num){  
  2.     $count=0;  
  3.     $result=array();  
  4.     while($count<$num){  
  5.         $result[]=mt_rand($min,$max);          //生成随机数时用了 mt_rand() 函数。这个函数生成随机数的平均速度要比 rand() 快四倍。    
  6.         $result=array_flip(array_flip($result));  //去除数组中的重复值时用了“翻翻法”,就是用 array_flip() 把数组的 key 和 value 交换两次。这种做法比用 array_unique() 快得多。  
  7.         $count=count($result);  
  8.     }  
  9.     shuffle($result);   //返回数组前,先使用 shuffle() 为数组赋予新的键名,保证键名是 0-n 连续的数字。如果不进行此步骤,可能在删除重复值时造成键名不连续,给遍历带来麻烦。  
  10.     return $result;  
  11. }  
  12. $arr=unique_rand(1,100,20);  
  13. $result="";  
  14. for($i=0;$i<count($arr);$i++){  
  15.     $result.=$arr[$i].",";  
  16. }  
  17. $result=substr($result,0,-1);  
  18. echo $result



正因为来之不易,所以才有了后来的倍加珍惜。
原文地址:https://www.cnblogs.com/jjxhp/p/6891950.html