在PHP数组中生成随机数

时间:2014-09-12 17:35:57

标签: php range

我有以下代码:

<?php

function randomGen($min, $max, $quantity) {
    $numbers = range($min, $max);
    shuffle($numbers);
    return array_slice($numbers, 0, $quantity);
}




for ($row = 0; $row < 5; $row++) {
  echo "<p><b>Set: $row</b></p>";

print_r(randomGen(1,36,6));
}
//}//}
?> 

例如输出:

Set: 0
Array ( [0] => 32 [1] => 35 [2] => 22 [3] => 29 [4] => 8 [5] => 17 ) 
Set: 1
Array ( [0] => 25 [1] => 28 [2] => 8 [3] => 30 [4] => 13 [5] => 9 ) 
Set: 2
Array ( [0] => 24 [1] => 31 [2] => 33 [3] => 28 [4] => 2 [5] => 32 ) 
Set: 3
Array ( [0] => 1 [1] => 6 [2] => 33 [3] => 2 [4] => 14 [5] => 29 ) 
Set: 4
Array ( [0] => 17 [1] => 25 [2] => 6 [3] => 15 [4] => 24 [5] => 22 ) 

但是我希望结果显示为:只有数字,例如:

32 35 22 29 8 17

ETC,我该如何去除它们

1 个答案:

答案 0 :(得分:2)

不要使用print_r() - 此功能本身也会打印索引。

$array = randomGen(1,36,6);
foreach($array as $key => $val){
    echo $val;
}

$key是您不想要的索引;我将其用于教育目的。

$array = randomGen(1,36,6);
foreach($array as $val){
    echo $val;
}