【发布时间】:2014-03-03 14:24:23
【问题描述】:
我正在使用 PHP rand 函数生成一个介于 1 和 6 之间的数字,并像这样执行 3 次:
echo rand(1, 6);
echo "<br>";
echo rand(1, 6);
echo "<br>";
echo rand(1, 6);
echo "<br>";
有没有办法防止相同的数字出现在 3 个随机数中的任何一个中?
【问题讨论】:
我正在使用 PHP rand 函数生成一个介于 1 和 6 之间的数字,并像这样执行 3 次:
echo rand(1, 6);
echo "<br>";
echo rand(1, 6);
echo "<br>";
echo rand(1, 6);
echo "<br>";
有没有办法防止相同的数字出现在 3 个随机数中的任何一个中?
【问题讨论】:
$random = range(1,6);
shuffle($random);
echo $random[0];
echo "<br>";
echo $random[1];
echo "<br>";
echo $random[2];
或
$input = range(1,6);
$random = array_rand($input);
echo $input[$random[0]];
echo "<br>";
echo $input[$random[1]];
echo "<br>";
echo $input[$random[2]];
【讨论】:
echo implode("\n", $random) . "\n";? ;P
array_shift 这样你就不用关心索引了。
试试这个代码
<?php
$out = array(); // We place generated values here
for ($i=0;$i<3;$i++ ) // 3 id the count of numbers
{
$r = rand(1,6);
while (in_array($r, $out)) { // if rand is already used then new rand
$r = rand(1,6);
}
echo $r.'<br />';
$out[] = $r;
}
?>
【讨论】:
$random = rand(1,6);
$random2 = rand(1,6);
while($random2==$random){
$random2 =rand(1,6);
}
$random3 = rand(1,6);
while($random3==$random||$random3==$random2){
$random3=rand(1,6);
}
echo $random."<br>";
echo $random2."<br>";
echo $random3."<br>";
【讨论】:
你使用 range()、array_shift() 和 shuffle() 函数来得到你想要的
$arr = range(0, 6);
shuffle($arr);
echo array_shift($arr);
echo array_shift($arr);
echo array_shift($arr);
echo array_shift($arr);
【讨论】:
$ar = range(1,6);
shuffle($ar);
echo implode('<br>', array_slice($ar,0,3)) . '<br>';
【讨论】: