How can I break an outer loop with PHP?

PhpFor LoopNested LoopsBreak

Php Problem Overview


I am looking to break an outer for/foreach loop in PHP.

This can be done in ActionScript like so:

top : for each(var i:MovieClip in movieClipArray)
{
	for each(var j:String in nameArray)
	{
		if(i.name == j) break top;
	}
}

What's the PHP equivalent?

Php Solutions


Solution 1 - Php

In the case of 2 nested loops:

break 2;

http://php.net/manual/en/control-structures.break.php

Solution 2 - Php

PHP Manual says

> break accepts an optional numeric > argument which tells it how many > nested enclosing structures are to be > broken out of.

break 2;

Solution 3 - Php

You can using just a break-n statement:

foreach(...)
{
    foreach(...)
    {
        if (i.name == j) 
            break 2; //Breaks 2 levels, so breaks outermost foreach
    }
}

If you're in php >= 5.3, you can use labels and gotos, similar as in ActionScript:

foreach (...)
{        
    foreach (...)
    {
        if (i.name == j) 
            goto top;
    }
}
top:

But goto must be used carefully. Goto is evil (considered bad practice)

Solution 4 - Php

You can use break 2; to break out of two loops at the same time. It's not quite the same as your example with the "named" loops, but it will do the trick.

Solution 5 - Php

$i = new MovieClip();
foreach ($movieClipArray as $i)
{
    $nameArray = array();
    foreach ($nameArray as $n) 
        if ($i->name == $n) 
            break 2;
}

Solution 6 - Php

Use goto?

for ($i = 0, $j = 50; $i < 100; $i++) 
{
  while ($j--) 
  {
    if ($j == 17) 
      goto end; 
  }  
}
echo "i = $i";
end:
echo 'j hit 17';

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartyView Question on Stackoverflow
Solution 1 - Phplucian303View Answer on Stackoverflow
Solution 2 - PhpShakti SinghView Answer on Stackoverflow
Solution 3 - PhpEdgar Villegas AlvaradoView Answer on Stackoverflow
Solution 4 - PhpJonView Answer on Stackoverflow
Solution 5 - PhpJordan ArsenoView Answer on Stackoverflow
Solution 6 - PhpPetr AbdulinView Answer on Stackoverflow