如何从随机函数中排除一个数字


How to exclude a number be be selected from a random function?

我正试图想出最简单的代码来从一个范围生成一个随机数,但不包括一个数字,在本例中为"2"。

我真的需要一个"如果"、"做"answers"暂时"来完成这件事吗?

<!DOCTYPE html>
<html>
<body>
<?php 
$x = rand(1,5);
if ($x == 2) {  
    do {
        echo "The number is: $x <br>";
        $x = rand(1,5);
    } while ($x == 2);
}
echo "The number is: $x <br>";
?>
</body>
</html>

您可以这样做:

$exclude = array(2);
while(in_array(($x = rand(1,5)), $exclude));
echo $x;

它之所以有效,是因为rand可能会在数组中返回一个变量,然后会重新触发while循环。

这样,您就可以构建一个包含所有要排除的数字的数组。

如果只排除一个数字,请将其替换为不包含在范围内的可接受数字。

<!DOCTYPE html>
<html>
<body>
<?php 
$x = rand(1,4); // accept 1, 2, 3 or 4 with equal probability
if ($x == 2) {  
    $x = 5; // if x = 2, change it to 5
}
echo "The number is: $x <br>";
?>
</body>
</html>