Exiting a loop early
Sometimes, when using a loop in PHP, you think to yourself "If this was a function, I could return here and not have to process the rest of this loop block". This sort of functionality inside of a loop is achievable, by using the break and / or continue statement.
The break statement will exit a loop, and accepts an optional argument to the number of nested loops to exit (see example below).
<?php
$people = array('henry', 'foo', 'jeff', 'bar', 'tom', 'barry');
foreach($people as $person) {
// stop at 'henry'
if ($person == 'henry') {
break;
}
}
?>In the example below, you can see that I've passed an argument to the break statement. The 2 here means that it will exit the parent loop.
<?php
$people = array('henry', 'foo', array('jeff', 'bar'), 'tom', 'barry');
foreach($people as $person) {
if (is_array($person) {
foreach($person as $innerPerson) {
if ($innerPerson == 'bar') {
break 2;
}
}
}
}
?>
You can use continue to do something similar but different to break. By using continue, it will halt the current loop and begin to iterate over the next array member (so long as the loop condition is still true).
<?php
$people = array('henry', 'foo', 'jeff', 'bar', 'tom', 'barry');
$bPeople = array();
foreach($people as $person) {
// we only want to process these people beginning with 'b'
if (strtolower($person[0]) != 'b') {
continue;
}
$bPeople[] = anotherLongComplexFunction($person);
}
?>This sort of thing can greatly remove the need for large nested if statements in your loops. It is also useful if they're is a complex operation in your loop, and bailing out early saves you process time.
Comments
No comments yet.
Leave a Comment
Note: Your comment may require approval before it is posted to the site.