How can I break an outer loop with PHP?

2019-01-11 05:31发布

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?

6条回答
Animai°情兽
2楼-- · 2019-01-11 05:47
    $i = new MovieClip();
    foreach($movieClipArray as $i)
    {
          $nameArray = array();
          foreach($nameArray as $n) if($i->name==$n) break 2;
    }
查看更多
祖国的老花朵
3楼-- · 2019-01-11 05:52

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 action script:

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

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

查看更多
劫难
4楼-- · 2019-01-11 05:53

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';
查看更多
倾城 Initia
5楼-- · 2019-01-11 06:05

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.

查看更多
唯我独甜
6楼-- · 2019-01-11 06:06

In the case of 2 nested loops:

break 2;

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

查看更多
做个烂人
7楼-- · 2019-01-11 06:10

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;
查看更多
登录 后发表回答