Combinations: avoid multiple nested foreach

When you need to check / have combinations of array elements, how can you avoid foreach nesting?

Code example:

$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?

+5
source share
4 answers

You can write your own Iterator class that implements the Iterator interface . Then you can use its constructor for three arrays, and then you can use it to loop through each combination using foreach.

, , . , foreach?

+7

, - . .

, , , "".

+2

, , , ? , .

+1

You did not give enough information to find out what the alternative is. If you really want to call method () with all combinations of options from $ as, $ bs and $ cs, then nested loops will do the right thing.

Is it multiple nested loops that bother you, or the fact that the () method is called count ($ as) * count ($ bs) * count ($ cs) times?

+1
source

All Articles