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));