无论是Web应用,还是WAP或者移动应用,随机数都有其用武之地。在最近接触的几个小项目中,我也经常需要和随机数或者随机数组打交道,所以,对于PHP如何产生不重复随机数常用的几种方法小结一下(ps:方法1、4、5是我常用的,其余来自网络整理)
方法1:
<span style="font-size:12px;"><?php
$numbers = range (1,50);
//shuffle 将数组顺序随即打乱
shuffle ($numbers);
//array_slice 取该数组中的某一段
$num=6;
$result = array_slice($numbers,0,$num);
print_r($result);
?></span>
方法2:
<span style="font-size:12px;"><?php
$numbers = range (1,20); //播下随机数发生器种子,可有可无,测试后对结果没有影响
srand ((float)microtime()*1000000);
shuffle ($numbers); //跳过list第一个值(保存的是索引)
while (list(, $number) = each ($numbers)) {
echo "$number ";
}
?></span>
方法3:
<span style="font-size:12px;"><?php
function NoRand($begin=0,$end=20,$limit=5){
<span style="white-space:pre"> </span>$rand_array=range($begin,$end);
<span style="white-space:pre"> </span>shuffle($rand_array); //调用现成的数组随机排列函数
<span style="white-space:pre"> </span>return array_slice($rand_array,0,$limit); //截取前$limit个
} <span style="font-family: Arial, Helvetica, sans-serif;">print_r(NoRand()); </span></span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size:12px;">?></span></span>
方法4:
<span style="font-size:12px;"><?php
$tmp=array();
while(count($tmp)<5){
<span style="white-space:pre"> </span>$tmp[]=mt_rand(1,20);
<span style="white-space:pre"> </span>$tmp=array_unique($tmp);
}
print_r($tmp);
?></span>
方法5:
<?php
$tmp = range(1,30);<span style="font-family: Arial;">print_r(array_rand($tmp,10)); ?></span>
这个可能是比叫简单的了(ps:如果在range中指定了步长,就必须注意array_rand的第二个参数是否超出$tmp的长度)。
PHP提供非常丰富的数组函数,产生随机数大多可以从数组这个角度出发,若你还有方法提供,欢迎给出,文章将持续更新。