PHP n个不重复的随机数生成代码,原理就是将数组顺序随即打乱 ,然取该数组中的某一段
代码如下:
<?php
//range 是将1到100 列成一个数组
$numbers = range (1,100);
//shuffle 将数组顺序随即打乱
shuffle ($numbers);
//array_slice 取该数组中的某一段
$no=6;
$result = array_slice($numbers,0,$no);
for ($i=0;$i<$no;$i++){
echo $result[$i].”
“;
}
print_r($result);
?>
//range 是将1到100 列成一个数组
$numbers = range (1,100);
//shuffle 将数组顺序随即打乱
shuffle ($numbers);
//array_slice 取该数组中的某一段
$no=6;
$result = array_slice($numbers,0,$no);
for ($i=0;$i<$no;$i++){
echo $result[$i].”
“;
}
print_r($result);
?>
代码如下:
//range 是将1到42 列成一个数组
$numbers = range (1,42);
//shuffle 将数组顺序随即打乱
shuffle ($numbers);
//array_slice 取该数组中的某一段
$result = array_slice($numbers,0,3);
print_r($result);
$numbers = range (1,42);
//shuffle 将数组顺序随即打乱
shuffle ($numbers);
//array_slice 取该数组中的某一段
$result = array_slice($numbers,0,3);
print_r($result);
方法2
代码如下:
<?php
$numbers = ra来源gao.dai.ma.com搞@代*码网nge (1,20);
srand ((float)microtime()*1000000);
shuffle ($numbers);
while (list (, $number) = each ($numbers)) {
echo “$number “;
}
?>
$numbers = ra来源gao.dai.ma.com搞@代*码网nge (1,20);
srand ((float)microtime()*1000000);
shuffle ($numbers);
while (list (, $number) = each ($numbers)) {
echo “$number “;
}
?>
方法3
用PHP,在1-20间随机产生5个不重复的值,如何做
代码如下:
<?php
function NoRand($begin=0,$end=20,$limit=5){
$rand_array=range($begin,$end);
shuffle($rand_array);//调用现成的数组随机排列函数
return array_slice($rand_array,0,$limit);//截取前$limit个
}
print_r(NoRand());
?>
function NoRand($begin=0,$end=20,$limit=5){
$rand_array=range($begin,$end);
shuffle($rand_array);//调用现成的数组随机排列函数
return array_slice($rand_array,0,$limit);//截取前$limit个
}
print_r(NoRand());
?>
或者不shuffle的话
代码如下:
<?php
$tmp=array();
while(count($tmp)<5){
$tmp[]=mt_rand(1,20);
$tmp=array_unique($tmp);
}
print join(‘,’,$tmp);
?>
$tmp=array();
while(count($tmp)<5){
$tmp[]=mt_rand(1,20);
$tmp=array_unique($tmp);
}
print join(‘,’,$tmp);
?>
以上就是PHP n个不重复的随机数生成代码的详细内容,更多请关注gaodaima搞代码网其它相关文章!