如何使用 PHP 中断外部循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5880442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I break an outer loop with PHP?
提问by Marty
I am looking to break an outer for/foreach loop in PHP.
我希望打破 PHP 中的外部 for/foreach 循环。
This can be done in ActionScript like so:
这可以在 ActionScript 中完成,如下所示:
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 等价物是什么?
回答by lucian303
In the case of 2 nested loops:
在 2 个嵌套循环的情况下:
break 2;
回答by Shakti Singh
PHP Manualsays
break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.
break 接受一个可选的数字参数,它告诉它要打破多少嵌套的封闭结构。
break 2;
回答by Edgar Villegas Alvarado
You can using just a break-n statement:
您可以只使用一个 break-n 语句:
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:
如果您在 php >= 5.3 中,您可以使用标签和goto
s,类似于在 ActionScript 中:
foreach (...)
{
foreach (...)
{
if (i.name == j)
goto top;
}
}
top:
But goto
must be used carefully. Goto is evil(considered bad practice)
但goto
必须谨慎使用。Goto 是邪恶的(被认为是不好的做法)
回答by Jon
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.
您可以使用break 2;
来同时跳出两个循环。它与您使用“命名”循环的示例不太一样,但它可以解决问题。
回答by Jordan Arseno
$i = new MovieClip();
foreach ($movieClipArray as $i)
{
$nameArray = array();
foreach ($nameArray as $n)
if ($i->name == $n)
break 2;
}
回答by Petr Abdulin
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';