您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php如何取随机数不重复?

2025/12/16 18:53:49发布20次查看
php取随机数不重复的方法:1、使用【rand(min,max)】函数产生随机数;2、使用【array_unique(arr)】对生成的数组进行去重;3、利用索引快速的生成不重复的随机数。
php取随机数不重复的方法:
首先想到的是rand(min,max)函数产生随机数,实际上使用mt_rand(min,max)能更加迅速的产生随机数。
其次使用array_unique(arr)对生成的数组进行去重,实际上使用array_flip(array_flip(arr))能更加快速的进行去重。
了解以上两点我们便可以写一个稍微优化过的函数:
/** * 生成指定长度不重复的字符串. * * @param integer $min 最小值. * @param integer $max 最大值. * @param integer $len 生成数组长度. * * @return array */function uniquerandom($min, $max, $len){ if ($min < 0 || $max < 0 || $len) { throw new logicexception('无效的参数'); } if ($max <= $min) { throw new logicexception('大小传入错误'); } $counter = 0; $result = array(); while ($counter < $len) { $result[] = mt_rand($min, $max); $result = array_flip(array_flip($result)); $counter = count($result); } shuffle($result); return $result;}
其实可以利用索引来更加快速的生成不重复的随机数,且效率甩上面函数几条街。
/** * 生成指定长度不重复的字符串. * * @param integer $min 最小值. * @param integer $max 最大值. * @param integer $len 生成数组长度. * * @return array */function uniquerandom2($min, $max, $len){ if ($min < 0 || $max < 0 || $len < 0) { throw new logicexception('无效的参数'); } if ($max <= $min) { throw new logicexception('大小传入错误'); } if (($max - $min + 2) < $len) { throw new logicexception("传入的范围不足以生成{$len}个不重复的随机数}"); } $index = array(); for ($i = $min; $i < $max + 1; $i++) { $index[$i] = $i; } $startone = current($index); $endone = end($index); for ($i = $startone; $i < $endone; $i++) { $one = mt_rand($i, $max); if ($index[$i] == $i) { $index[$i] = $index[$one]; $index[$one] = $i; } } return array_slice($index, 0, $len);}
该算法与上面算法相比巧妙之处在于:
对自增索引进行随机,不会有重复的问题,避免了去重的开销
用数组下标替代数组本身进行随机,每取到一个随机数后就将其在取值范围中排除,下一次仅会在剩下的数字中取,一次遍历就可以完成随机数的选取。
相关学习推荐:php编程从入门到精通
以上就是php如何取随机数不重复?的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product