PHP Continue Statement
The continue statement in PHP is used to skip the current iteration of a loop and continue with the next iteration. This can be particularly useful for filtering out specific conditions within loops.
1. Using continue in Loops
The continue statement can be used in for, while, and do-while loops. When encountered, it skips the remaining code in the current iteration and jumps to the next iteration of the loop.
// Example with a for loop
for ($i = 0; $i < 10; $i++) {
if ($i % 2 == 0) {
continue; // Skip even numbers
}
echo $i . " "; // Output odd numbers
}
// Output: 1 3 5 7 92. Using continue in a while Loop
The continue statement can also be applied within a while loop. This allows you to control which iterations should be processed.
// Example with a while loop
$i = 0;
while ($i < 10) {
$i++;
if ($i % 2 == 0) {
continue; // Skip even numbers
}
echo $i . " "; // Output odd numbers
}
// Output: 1 3 5 7 93. Using continue with a Numeric Argument
You can also use the continue statement with a numeric argument in nested loops. This allows you to skip to the next iteration of a specific level of the loop.
// Example with nested loops
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
if ($j == 2) {
continue 2; // Skips to the next iteration of the outer loop
}
echo "i = $i, j = $j\n";
}
}
// Output: i = 1, j = 1
// i = 2, j = 1
// i = 3, j = 1Conclusion
The continue statement is a valuable tool in PHP for controlling the flow of loops. It enables you to efficiently skip iterations based on specific conditions, which can help optimize code execution.