Quit two PHP Foreachs

Asked

Viewed 218 times

7

I need to iterate several Collections and if I find a condition I should leave 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 that ?

2 answers

11


You can also use break 2 to get out of both 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 numerical argument (2) serves to indicate how many nested structures the break must interrupt, see more here.

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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.