Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I break an outer loop with PHP?

People also ask

How do you break out of a loop in a loop?

Breaking Out of For Loops. To break out of a for loop, you can use the endloop, continue, resume, or return statement.

How do you break an inner and outer loop?

There are two steps to break from a nested loop, the first part is labeling loop and the second part is using labeled break. You must put your label before the loop and you need a colon after the label as well. When you use that label after the break, control will jump outside of the labeled loop.

Does Break stop all loops PHP?

The break statement is used to ends the execution of the current loop or switch case statement in PHP. But when working with nested loops and wants to exit out from all or some of the outer loops. For this, you need to pass numeric value following with break statement.

How do you end a while loop in PHP?

The keyword break ends execution of the current for, foreach, while, do while or switch structure. When the keyword break executed inside a loop the control automatically passes to the first statement outside the loop.


In the case of 2 nested loops:

break 2;

http://php.net/manual/en/control-structures.break.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;

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)


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.


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

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