PHP Continue
In PHP, the continue
statement is used within loop constructs to skip the rest of the current iteration and continue with the next iteration of the loop. It is often used in loops to skip specific iterations based on certain conditions without terminating the loop entirely.
Here's how continue
works in different loop constructs:
For Loop
for ($i = 0; $i < 5; $i++) {
if ($i == 2) {
continue; // Skip iteration when $i equals 2
}
echo $i . ' ';
}
// Output: 0 1 3 4
While Loop
$i = 0;
while ($i < 5) {
$i++;
if ($i == 2) {
continue; // Skip iteration when $i equals 2
}
echo $i . ' ';
}
// Output: 1 3 4 5
Foreach Loop
$arr = [1, 2, 3, 4, 5];
foreach ($arr as $value) {
if ($value == 3) {
continue; // Skip iteration when $value equals 3
}
echo $value . ' ';
}
// Output: 1 2 4 5
The continue
statement works similarly in all loop constructs. When encountered, it immediately stops the current iteration and continues with the next iteration of the loop. Any code following the continue
statement within the loop block is skipped for the current iteration.