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?
There's no built-in ability to break in forEach . To interrupt execution you would have to throw an exception of some sort.
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.
break ends execution of the current for , foreach , while , do-while or switch structure.
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.
Use the break
statement inside the if condition:
if ($small_object->TIME == $sought_time) {
break;
}
break
statement will break out of the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With