Skip to main content

The PHP Break Statement

Sometimes a loop has done its job before it reaches its natural end. The break statement handles this case: the moment PHP reaches it, the whole loop stops and the script carries on with whatever comes after the loop.

It works in all four loop types:

  • for
  • while
  • do...while
  • foreach

PHP break Out of a for Loop

Inside a for loop, break ends the loop right away, even if the counter has not reached its limit yet.

Break Out of For Loop

The counter could go up to 9, but this loop ends as soon as $x reaches 4, so the last number printed is 3:

Prompt
Write a PHP script that uses a for loop from 0 to 9, breaks out of the loop when the counter equals 4, and prints the number on each iteration.
Output: PHP script

PHP break Out of a while Loop

A while loop can be cut short in the same way, even though its condition is still true.

Break Out of While Loop

The condition allows values below 10, yet the loop stops once $x equals 4:

Prompt
Write a PHP script that uses a while loop from 0 to 9, breaks out of the loop when the counter equals 4, and prints the number on each iteration.
Output: PHP script

PHP break Out of a do...while Loop

Placing break inside a do...while loop means the condition at the bottom is never checked again: PHP leaves the loop straight away.

Break Out of Do While Loop

As soon as $i equals 3, the loop ends, which leaves only 1 and 2 in the output:

Prompt
Write a PHP script that uses a do...while loop up to 6, breaks out of the loop when the counter equals 3, and prints the counter value on each iteration.
Output: PHP script

PHP break Out of a foreach Loop

With foreach, break lets you stop before all the array elements have been visited, which is handy once you have found what you were looking for.

Break Out of Foreach Loop

The loop walks through the colors and stops on reaching "blue", so neither "blue" nor "yellow" gets printed:

Prompt
Write a PHP script that uses a foreach loop over an array of colors and breaks out of the loop when the value is "blue", printing each color before breaking.
Output: PHP script