As the volume of blacklisted integers approaches the size of the whole range of integers, it becomes more and more convincing to listen to @regenschein's advice.
A non-iterative approach might look like this:
$range = range(1, 1600); $blacklist = [234, 1578, 763, 1274]; // 4 blacklisted versus 1600 full range is NOT compelling $valids = array_diff($range, $blacklist); echo array_values($valids)[rand(0, count($valids) - 1)]; // or echo $valids[array_rand($valids)]; // the two approaches use different randomizers
Or, if you are just as happy, you can do:
$blacklist = [234, 1578, 763, 1274]; $range = range(1, 1600); $valids = array_diff($range, $blacklist); shuffle($valids); echo $valids[0];
* Please note that array_diff() especially array_diff() if you want to pass multiple arrays of blacklist - just separate them with commas.
For instance:
var_export($valids = array_diff(range(1, 100), range(5, 50), range(61, 99), [55]));
Output:
array ( 0 => 1, 1 => 2, 2 => 3, 3 => 4, 50 => 51, 51 => 52, 52 => 53, 53 => 54, 55 => 56, 56 => 57, 57 => 58, 58 => 59, 59 => 60, 99 => 100, )