When you need to check/have combinations of array elements, how can you avoid nesting foreach?
Example code:
$as = array($optionA1, $optionA2)
$bs = array($optionB1, $optionB2)
$cs = array($optionC1, $optionC2)
foreach ($as as $a) {
foreach ($bs as $b) {
foreach ($cs as $c) {
$result = $this->method($a, $b, $c);
if ($result) etc
}
}
}
Anyone with alternative approaches that can avoid nesting?
You could write your own Iterator class which implements the Iterator interface. You could then have its constructor accept the three arrays and then you can use it to loop over every combination with foreach.
However I think this would be significantly slower, so I would avoid it. It would be interesting to know the reasons you want to avoid the nested foreach loops?
Logically, you have to iterate through each item somehow. You're just shuffling around the process.
If multiple for loops look ugly, maybe you should put your arrays into their own classes, that have their own encapsulated 'checks'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With