'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?
Solution 1:[1]
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.
Solution 2:[2]
Use the break  statement inside the if condition:
if ($small_object->TIME == $sought_time) {
   break;       
}
break statement will break out of the loop.
Solution 3:[3]
   $count = 0;
    ......
    ..
    ..
    ..
    ..
    ......    
    if (++$count == 5) break;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | ciruvan | 
| Solution 2 | eMpTy43 | 
| Solution 3 | lookly Dev | 
