PHP Break & Continue
The break statement immediately ends the loop (or switch) it is inside, jumping to the code right after it. The continue statement skips the rest of the current iteration and moves on to the next one.
Both keywords give you finer control over loop execution, letting you exit early when a condition is met or skip specific items without processing the entire loop body.
break;
continue;Using break
break is often used to stop a loop as soon as a certain value is found, avoiding unnecessary further iterations once the goal has been reached.
Using continue
continue is useful for skipping items that don't need processing, such as skipping even numbers while summing only odd numbers.
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 4) {
break;
}
echo $i . " ";
}
?>1 2 3 The loop stops completely as soon as $i equals 4.
<?php
for ($i = 1; $i <= 5; $i++) {
if ($i % 2 == 0) {
continue;
}
echo $i . " ";
}
?>1 3 5 continue skips printing whenever $i is even, moving straight to the next iteration.
Key points
- break exits the loop entirely.
- continue skips only the current iteration.
- Both can be used in while, do-while, for and foreach loops.
- break also exits a switch statement's current case.
