PHP Break and Continue
Break leaves a loop at once. Continue skips the rest of the current round and starts the next round.
Break stops a for loop
The break runs when the counter reaches 3. The numbers 3, 4 and 5 never print.
<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
break;
}
echo $i . "\n";
}Continue skips one value
The continue runs when the counter is 3. That round prints nothing, and the loop carries on.
<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue;
}
echo $i . "\n";
}Break leaves a while loop early
The while test allows values up to 10. The break ends the loop when the counter reaches 4.
<?php
$i = 1;
while ($i <= 10) {
if ($i == 4) {
break;
}
echo $i . "\n";
$i++;
}Example
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 3) {
continue;
}
if ($i == 6) {
break;
}
echo $i . "\n";
}Key points
- A break statement stops the loop and the program moves past it.
- A continue statement skips the rest of the current round and starts the next round.
- Break also ends a case in a switch.
- An if test often guards a break or a continue inside a loop.
In this example, the loop heads toward 10. The value 3 is skipped by continue, so it never prints. The break runs at 6, so the printed numbers stop after 5.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz PHP Compiler
Exercise
What does continue do inside a loop?