Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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?

like image 227
Edward Avatar asked Aug 02 '13 08:08

Edward


People also ask

Can you break out of foreach?

There's no built-in ability to break in forEach . To interrupt execution you would have to throw an exception of some sort.

How do you end a foreach loop?

To terminate the control from any loop we need to use break keyword. The break keyword is used to end the execution of current for, foreach, while, do-while or switch structure.

Does Break stop foreach?

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


2 Answers

From PHP documentation:

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

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

like image 159
ciruvan Avatar answered Oct 04 '22 03:10

ciruvan


Use the break statement inside the if condition:

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

break statement will break out of the loop.

like image 25
Code Lღver Avatar answered Oct 04 '22 02:10

Code Lღver