Edward Edward - 11 months ago 48
PHP Question

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?

Answer Source

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.