• Home
  • PHP continue statement – What does PHP continue do?

PHP continue statement – What does PHP continue do?

The continue statement is a control statement in PHP that allows you to skip the rest of the current iteration of a loop and move on to the next one. It is particularly useful for skipping over certain elements of an array or for ignoring certain conditions in a loop.

The syntax for the continue statement in PHP is as follows:

continue;

The continue statement can be used inside any type of looping statement, including while loops, do...while loops, for loops, and foreach loops. It causes the loop to skip the rest of the current iteration and move on to the next one, without terminating the loop.

Here is an example of using the continue statement to skip certain elements of an array:

$array = array(1, 2, 3, 4, 5);
foreach ($array as $value) {
if ($value % 2 == 0) {
continue;
}
echo $value . "\n";
}

This code will output the numbers 1 and 3, because the continue statement causes the loop to skip over the even numbers 2 and 4.

You can also use the continue statement with a label to skip the rest of the current iteration of a nested loop or a loop that is not the innermost loop. A label is simply an identifier followed by a colon, placed before the loop statement.

Here is an example of using a label and the continue statement to skip certain iterations of a nested loop:

outer:
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
if ($i == 2 && $j == 2) {
continue outer;
}
echo $i . "," . $j . "\n";
}
}

This code will output the strings “1,1”, “1,2”, “1,3”, “2,1”, “3,1”, “3,2”, and “3,3”, because the continue statement with the label “outer” causes the inner loop to skip the iteration when $i is 2 and $j is 2.

The continue statement is particularly useful for skipping over certain elements of an array or for ignoring certain conditions in a loop. It allows you to control the flow of the loop without terminating it, which can be more efficient than using a break statement and starting the loop over again.