PHP : Continue

In PHP, the continue statement is used to skip the rest of the current iteration in a loop and continue with the next iteration. It's often used within loops to bypass certain iterations based on specific conditions without exiting the loop entirely. Here's how you can use continue:


foreach ($array as $value) {
    // code to be executed for each iteration

    if ($condition) {
        continue; // skip the rest of the current iteration and continue with the next iteration
    }

    // code here will not be executed if the condition is met

}
 

In this syntax:

  • continue is the keyword used to skip the current iteration.
  • It can be placed inside the loop body.
  • When PHP encounters the continue statement, it skips the remaining code in the current iteration and jumps to the next iteration.

Here's an example of using continue in a foreach loop:


$numbers = array(1, 2, 3, 4, 5);

foreach ($numbers as $number) {
    if ($number == 3) {
        continue; // skip printing 3
    }

    echo $number . "<br>";
}

echo "Loop ended.";
 

This will output:


1
2
4
5
Loop ended.

 

In this example, when $number is 3, the continue statement is executed, causing the loop to skip the echo statement and move to the next iteration. As a result, the number 3 is not printed, and the loop continues with the next values in the array.