Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combinations: avoiding multiple nested foreach

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?

like image 739
koen Avatar asked Jul 23 '09 18:07

koen


2 Answers

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?

like image 173
Tom Haigh Avatar answered Sep 30 '22 09:09

Tom Haigh


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'.

like image 30
Rob Elliott Avatar answered Sep 30 '22 09:09

Rob Elliott