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:
forwhiledo...whileforeach
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:
Output: PHP script
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
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:
Output: PHP script
<?php
$x = 0;
while($x < 10) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
$x++;
}
?>
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:
Output: PHP script
<?php
$i = 1;
do {
if ($i == 3) break;
echo $i;
$i++;
} while ($i < 6);
?>
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:
Output: PHP script
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
if ($value == "blue") break;
echo "$value<br>";
}
?>