cronos cronos - 7 months ago 9
PHP Question

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

I am trying to come up with the simplest code to generate a random number from a range but excluding one number, in this case "2".

Do I really need an "if" a "do" and a "while" to accomplish this?

<!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>

Answer

You can do this:

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

It works because the rand may return a variable in the array, which would then retrigger the while loop.

With this, you can build an array of all the numbers you want to exclude.