Nic*_*lla -1 php arrays random loops
我想在数组中添加5个随机数,但每个数字必须不同.这是我到目前为止所拥有的......
$col_B = array();
for ($i=1; $i < 6; $i++) {
$rand = $col_ranges['B'][rand ( 0 , 14 )]; // calls to an array of numbers
if(!in_array($rand, $col_B)){
$col_B[] = $rand;
}
else{ $i - 1;}
}
echo implode($col_B, '<br>');
Run Code Online (Sandbox Code Playgroud)
我不会在这里使用for循环,而是执行while循环,直到随机数数组达到所需的计数.您的问题是,$i无论您是否添加$rand到阵列,都会继续增加.
$col_B = array();
while( count($col_B) < 5 )
{
$rand = $col_ranges['B'][rand ( 0 , 14 )]; // calls to an array of number
if( ! in_array($rand, $col_B) )
$col_B[] = $rand;
}
Run Code Online (Sandbox Code Playgroud)