php 一旦满足条件,如何跳出 foreach?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18012290/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:48:12  来源:igfitidea点击:

How to break out of a foreach once a condition is met?

phploopsforeachconditional

提问by Edward

I have a situation where when dealing with an object I generally use a foreach to loop through it like this:

我有一种情况,在处理对象时,我通常使用 foreach 像这样循环遍历它:

foreach ($main_object as $key=>$small_object) {
...

}

However, I need to put a conditional in there like this:

但是,我需要在其中放置一个条件,如下所示:

foreach ($main_object as $key=>$small_object) {
   if ($small_object->NAME == "whatever") {
      // We found what we need, now see if he right time.
      if ($small_object->TIME == $sought_time) {
          // We have what we need, but how can we exit this foreach loop?
      }
}

What is the elegant way to do this? It seems wasteful to have it keep looping through if it's found a match. Or is there another approach to do this that is better? Possibly using for instead of foreach?

这样做的优雅方法是什么?如果找到匹配项,让它继续循环似乎很浪费。或者是否有另一种更好的方法来做到这一点?可能使用 for 而不是 foreach?

回答by ciruvan

From PHP documentation:

来自 PHP 文档:

breakends execution of the current for, foreach, while, do-while or switch structure.

break结束当前 for、foreach、while、do-while 或 switch 结构的执行。

So yes, you can use it to get out of the foreach loop.

所以是的,您可以使用它来退出 foreach 循环。

回答by Code L?ver

Use the breakstatement inside the if condition:

使用breakif 条件中的语句:

if ($small_object->TIME == $sought_time) {
   break;       
}

breakstatement will break out of the loop.

break语句将跳出循环。