Breaking Out of For Loops. To break out of a for loop, you can use the endloop, continue, resume, or return statement.
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.
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.
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 goto
s, 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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With