No built-in function, but you could do this:
function randWithout($from, $to, array $exceptions) {
sort($exceptions); // lets us use break; in the foreach reliably
$number = rand($from, $to - count($exceptions)); // or mt_rand()
foreach ($exceptions as $exception) {
if ($number >= $exception) {
$number++; // make up for the gap
} else /*if ($number < $exception)*/ {
break;
}
}
return $number;
}
That's off the top of my head, so it could use polishing - but at least you can't end up in an infinite-loop scenario, even hypothetically.
Note: The function breaks if $exceptions
exhausts your range - e.g. calling randWithout(1, 2, array(1,2))
or randWithout(1, 2, array(0,1,2,3))
will not yield anything sensible (obviously), but in that case, the returned number will be outside the $from
-$to
range, so it's easy to catch.
If $exceptions
is guaranteed to be sorted already, sort($exceptions);
can be removed.
Eye-candy: Somewhat minimalistic visualisation of the algorithm.