How to break out of a for each loop early with PHP

Leave for each early with php

There are many times in programming you will need to loop items, whether that is arrays, objects, or JSON. In some cases, you don't need to iterate over every single item in the array in order to find what you're looking for. This is because you'll experience a performance hit if you don't exit early. In other words, you're unnecessarily looping, wasting time checking other items when you've already found what you're looking for. PHP has a list of built-in reserved keywords, but the one we need here to exit for each (foreach) early is 'break'.

An example of how to leave a for each early would look similar to this.

# PHP 7.x and above
$array = [
'not item',
'not this one',
'item we are looking for',
'this will never get checked'
];

foreach ($array as $item) {
 if ($item === 'item we are looking for') {
 echo 'Yes, we have found it!';
 break;
 }
}

You may wish to instead of looping and breaking a for each, you might want to consider array_search instead. Array searching vs. looping an array is considered quicker;

if (array_search('item we are looking for', $array, true) !== false) {
 echo 'Yes, we have found it!';
}

In which case you've now got fewer lines of code and a slightly quicker function. The performance gains here only are noticeable with a bigger array of items, but having fewer lines of cleaner code is sometimes better.

Another example of using a break inside a loop is within a while or do-while statement. It works for any looping literation method in PHP, but here, we break out of the while loop once the count of the variable "i" is equal to three. You can also use the PHP break statement to break out of a nested loop, to avoid even more wasted CPU time.

$i = 0;

while (true) {
 $i++;

 // Break once the count reaches greater than 3
 if ($i === 3) {
 break;
 }
}

When to use 'continue' within looping structures?

You might see the reserved keyword 'continue' being used in conjunction with other PHP methods. Continue holds a similar action to break, but instead skips the current loop and tells PHP to move on. Whereas, a break will leave the for each loop completely.

An example of when you might use continue instead of break would be something like this.

$animalArray = [
 1 => 'number 1',
 'cat' => 'meow',
 2 => 'number 2',
 'dog' => 'woof',
];

foreach ($animalArray as $key => $value) {
 // Only echo animal sounds (not numbers)
 if (is_numeric($key)) {
 continue;
 }
 echo $value;
}

What is break 2?

By default the behaviour of break is to leave the immediate enclosed structure, which is one level, but it is possible to provide an optional numeric argument to break to tell the PHP engine how many nested structures are to be broken out from. This is particularly useful when your code has nested loops, maybe 2 or 3 levels deep (for example) and you may wish to break more than one level at a time. As more loops get nested it tends to impact performance, so breaking for example twice at a time is very useful, such as "break 2".

Cannot 'break' 2 levels

When specifying the break level in PHP, be sure to only include the correct level number that matches the less than or equal to the total number of structures. If you have a single foreach loop, putting break 2 in your code, will cause PHP to issue a fatal error, similar to "Fatal error: Cannot 'break' 2 levels". If you experience this fatal error, be sure to check your code and ensure you are not attempting to break out of more levels than you working with.

Misplaced break

When using the "break" keyword in PHP be careful not to put the keyword outside of a loop or switch structure, otherwise, you'll trigger a fatal error in PHP. In the below PHP code example, you'll see that the break is outside the while loop. Because break can only be used in a loop or switch you'll get: "Fatal error: 'break' not in the 'loop' or 'switch' context" error. To fix this, ensure that the break keyword is placed inside one of these structures.

while ($x < 10) {
 // code here
}
break; // Putting this here will trigger an error

Unreachable PHP code

Using breaks in your PHP code is a great way to speed up your application, but a common "gotcha" is putting a break before indented code. By using a break, once the PHP parsing engine reaches this part of the code, it will not execute anything else under it. Whilst this won't trigger an error or warning this is a common unintended problem people face. In the example below you will see that the code following the break will never get executed, and likely that's not intentional. Luckily most PHP IDE's such as PHPStorm will alert you to this fact so it can be resolved. The below code snippet gives you an example of this.

foreach ([1,2,3] as $value) {
 if ($value == 3) {
 break;
 echo "This code will never be executed.";
 }
}

Missing break in Switch case

A common mistake when working with switch case statements is forgetting to add the break keyword at the end of each switch case. By not having a break inside the case the PHP engine will continue to execute code underneath it. Let's take the following example if our switch statement matches the number one, we'll get an echo output of "Case 1", but because this case has no break, it'll continue and output "Case 2" as well. In nearly all situations, this isn't the desired result. If using a switch statement it's always remember to place "break;" at the end of each case.

switch (1) {
 case 1:
 echo 'Case 1';
 case 2:
 echo 'Case 2';
 break;
}

Conclusion

Understanding that it is possible to break out of a loop early will not only use less server memory but also improve the response time of the PHP script in question. Using the correct keyword (break vs. continue) when working with loops is essential.

  • Use 'break' to completely leave a for each early
  • Use 'continue' to skip to the next iteration without leaving the loop
  • If you need to iterate over all items in the loop, don't break
  • You don't need to add a break or continue once the loop has finished, it's only required if you're done mid-point
  • As break and continue are reserved PHP keywords, try not to set variables with the same name to avoid confusion
  • You can use a break on for, foreach, while, do-while, or switch statements
  • Use a break followed by a numeric value to break more than one nested structure

Senior PHP developer with near two decades of PHP experience. Author of Dev Lateral guides and tools. The complete place for PHP programmers. Available to hire to help you build or maintain your PHP application.

Looking for industry-leading PHP web development?

API development WordPress Hosting ★ and more 🐘

We use cookies to enhance your browsing experience and analyse website traffic in accordance with our Privacy and Cookie Policy. Our cookies, including those provided by third parties, collect anonymous information about website usage and may be used for targeted advertising purposes. By clicking "Reject non-essential" you can opt out of non-essential cookies. By clicking "Accept all" you agree to the use of all cookies.


Reject non-essential Accept all