I have a loop that is doing some error checking in my PHP code. Originally it looked something like this...
foreach($results as $result) {
if (!$condition) {
$halt = true;
ErrorHandler::addErrorToStack('Unexpected result.');
}
doSomething();
}
if (!$halt) {
// do what I want cos I know there was no error
}
This works all well and good, but it is still looping through despite after one error it needn't. Is there a way to escape the loop?
As stated in other posts, you can use the break keyword. One thing that was hinted at but not explained is that the keyword can take a numeric value to tell PHP how many levels to break from.
For example, if you have three foreach loops nested in each other trying to find a piece of information, you could do 'break 3' to get out of all three nested loops. This will work for the 'for', 'foreach', 'while', 'do-while', or 'switch' structures.
$person = "Rasmus Lerdorf";
$found = false;
foreach($organization as $oKey=>$department)
{
foreach($department as $dKey=>$group)
{
foreach($group as $gKey=>$employee)
{
if ($employee['fullname'] == $person)
{
$found = true;
break 3;
}
} // group
} // department
} // organization