The continue statement skips the rest of the current loop iteration and moves to the next one. Using levels lets you skip iterations in outer loops when you have nested loops.
0
0
Continue statement with levels in PHP
Introduction
When you want to skip the rest of the current loop iteration and continue with the next one.
When you have nested loops and want to skip iterations in an outer loop from inside an inner loop.
When processing multi-level data and you need to jump to the next item at a specific loop level.
When you want to avoid deeply nested if-else blocks by skipping iterations early.
Syntax
PHP
continue; // skips current iteration of the innermost loop continue n; // skips current iteration of the nth enclosing loop
The n in continue n; must be a positive integer.
If n is omitted, it defaults to 1, meaning the innermost loop.
Examples
This skips printing when
$j is 2, but continues the inner loop.PHP
<?php for ($i = 1; $i <= 3; $i++) { for ($j = 1; $j <= 3; $j++) { if ($j == 2) { continue; // skips to next $j iteration } echo "$i,$j "; } } ?>
This skips the rest of the inner and outer loop iteration when
$j is 2, moving to the next $i.PHP
<?php for ($i = 1; $i <= 3; $i++) { for ($j = 1; $j <= 3; $j++) { if ($j == 2) { continue 2; // skips to next $i iteration } echo "$i,$j "; } } ?>
Sample Program
This program uses continue 2; to skip the rest of both loops' current iterations when $j is 2. It shows how the outer loop moves on early.
PHP
<?php for ($i = 1; $i <= 3; $i++) { echo "Outer loop i=$i\n"; for ($j = 1; $j <= 3; $j++) { if ($j == 2) { echo " Skipping inner loop j=$j with continue 2\n"; continue 2; // skips to next iteration of outer loop } echo " Inner loop j=$j\n"; } } ?>
OutputSuccess
Important Notes
Using continue with levels helps control complex nested loops clearly.
Be careful: skipping outer loops can make code harder to read if overused.
Always test nested loops with continue n; to ensure the flow is what you expect.
Summary
continue skips the rest of the current loop iteration.
continue n; skips iterations in outer loops when nested.
This helps manage nested loops cleanly and avoid extra checks.