Home > Backend Development > PHP Tutorial > 碰到怪事了 PHP 设定了range范围 但运行结果却是显示在范围之外,为什么?

碰到怪事了 PHP 设定了range范围 但运行结果却是显示在范围之外,为什么?

WBOY
Release: 2016-06-20 12:45:29
Original
869 people have browsed it

一段PHP随机代码,设定了range(1,30)但多次运行结果会显示出0,why?
代码:
$red1=range(1,30);
$sc1=array_rand($red1,8);
?>


foreach($sc1 as $v){
echo "$v ";
}
?>

$red2=range(1,30);
$sc1=array_rand($red2,8);
?>

foreach($sc1 as $v){
echo "$v ";
}
?>
$red1=range(1,30);
$sc1=array_rand($red1,8);
?>

foreach($sc1 as $v){
echo "$v ";
}
?>

$red2=range(1,30);
$sc1=array_rand($red2,8);
?>

foreach($sc1 as $v){
echo "$v ";
}
?>
请多刷新几次,第一个数竟然会出现0?。。为什么?


回复讨论(解决方案)

你想要的应该是打乱数组排序,取8个元素出来是吧?

shuffle($red1);
$red1 = array_splice($red1,0,8);

array_rand()随机取出来的是键名;

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template