Billy - 10 months ago 37

PHP Question

How would I generate a random number from a range of numbers between 1 and 10 while excluding an array of numbers e.g. 4,5,6.

`$exclude = array(4,5,6);`

The following code allows to generate random numbers within a range however only for a single number and not an array of numbers

`function randnumber() {`

do {

$numb = rand(1,10);

} while ($varr == 4);

return $numb;

}

Answer

Create a loop that iterates until a generated random number using rand function is not in array. If the generated number is found in array, again another random number is generated.

```
do {
$number = rand(1,10);
} while(in_array($number, array(4,5,6)));
echo $number;
```

or

```
while(in_array(($number = rand(1,10)), array(4,5,6)));
echo $number;
```

You can use it like a function too:

```
<?php
function randomNo($min,$max,$arr) {
while(in_array(($number = rand($min,$max)), $arr));
return $number;
}
echo randomNo(1,10,array(4,5,6));
```

The above function, does the same process, in addition, you can reuse the code. It gets minimum and maximum number and the array of values to exclude.

Finally,

without loop, but with recursive function. The function generates a random number and returns if it is not found in the `exclude`

array:

```
function randomExclude($min, $max, $exclude = array()) {
$number = rand($min, $max);
return in_array($number, $exclude) ? randomExclude($min, $max, $exclude) : $number;
}
echo randomExclude(1,10,array(4,5,6));
```