Exit two Foreachs PHP

7

I need to iterate several collections and if I find a condition I have to exit more than one iteration loop.

Ex:

    foreach ($order->getItemCollection() as $item) {
        foreach ($order->getFreight()->getPackageCollection() as $packs) {
            foreach ($packs->getItemCollection() as $packItem) {
                if ($item->getSku() == $packItem->getSku()) {
                    ...
                    break ;
                }
            }
        }
    }

How can I do this?

    
asked by anonymous 06.10.2014 / 20:47

2 answers

11

You can also use break 2 to exit the two loop´s :

Example: Ideone

foreach ($order->getItemCollection() as $item) {
     foreach ($order->getFreight()->getPackageCollection() as $packs) {
         foreach ($packs->getItemCollection() as $packItem) {
             if ($item->getSku() == $packItem->getSku()) {
                 ...
                 break 2 ;
             }
         }
     }
 }

The numeric argument (2) is to indicate how many nested structures the break should break, view more here.

    
06.10.2014 / 21:01
3

You can use a variable;

$sair = FALSE;
foreach ($order->getItemCollection() as $item) {
    foreach ($order->getFreight()->getPackageCollection() as $packs) {
        foreach ($packs->getItemCollection() as $packItem) {
            if ($item->getSku() == $packItem->getSku()) {
                ...
                $sair = true;
            }
            if ($sair) break;
        }
        if ($sair) break;
    }
    if ($sair) break;
}
    
06.10.2014 / 20:51