Sometimes you need to stop a loop early or skip certain parts of its code based on a specific condition. PHP provides two powerful keywords for this purpose: break and continue.
The break statement is used to jump out of a loop entirely. Once a break is encountered, PHP stops the loop and continues with the first line of code after the loop block.
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break; // Exits the loop completely when $x is 4
}
echo "The number is: $x <br>";
}
?>
The continue statement breaks one iteration (in the loop). If a specified condition occurs, it skips the rest of the code in that iteration and jumps to the next one.
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue; // Skips 4 and goes straight to 5
}
echo "The number is: $x <br>";
}
?>
break and continue work in all types of PHP loops: for, while, do while, and foreach.
break when searching through data (e.g., stop looping once the specific user is found) to save processing power.
Breaking a loop helps prevent infinite execution or unnecessary processing.
<?php
$x = 0;
while($x < 100) {
if ($x == 10) {
break;
}
echo "Number: $x <br>";
$x++;
}
?>
if condition inside the loop.break can improve performance by stopping unnecessary work.