I have the following problem but I will simplify it here:
$starting = 0; $arrayOfNumbersToSkip = [1, 3, 4, 5, 6]; $ending = 7;
Part 1: Give me the first number available? “Answer is 2”
Part 2: Give me the next number available? “Answer is 7”
This is a simplified version of a math problem im facing, im designing a dynamic approval system that modifies the entire program based on changeable rules.
Advertisement
Answer
You could use array_diff with a range from $starting+1 to $ending:
$availableNumbers = array_diff(range($starting+1, $ending), $arrayOfNumbersToSkip);
if (!count($availableNumbers)) {
echo "no numbers availablen";
}
else {
echo "first number available = " . array_shift($availableNumbers);
}
print_r($availableNumbers);
Output:
first number available = 2
Array
(
[0] => 7
)
The output shows that there are still available numbers (you can keep using array_shift to get them) after taking 2 from the array.