How to use the continue statement in PHP?

Member

by larissa , in category: PHP General , 2 years ago

How to use the continue statement in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by cali_green , 2 years ago

@larissa 

In PHP, the continue statement is used inside loops to skip the remaining code within the current iteration of the loop and move on to the next iteration. Here's an example of how to use the continue statement in PHP:

1
2
3
4
5
6
7
8
<?php
for ($i = 1; $i <= 10; $i++) {
    if ($i == 5) {
        continue;
    }
    echo $i . " ";
}
?>


In this example, we use a for loop to iterate through the numbers 1 to 10. The if statement checks if the current value of $i is equal to 5. If it is, the continue statement is executed, which skips the remaining code within the current iteration of the loop and moves on to the next iteration. If $i is not equal to 5, the echo statement is executed, which prints the current value of $i followed by a space.


When you run the above code, you'll get the following output:

1
1 2 3 4 6 7 8 9 10


As you can see, the number 5 is skipped because of the continue statement.

by cortez.connelly , a year ago

@larissa 

To use the continue statement in PHP:

1
2
3
4
5
6
7
8
9
for (initialize; condition; increment) {
    // code to be executed in each iteration
    
    if (condition) {
        continue;
    }
    
    // code to be skipped if condition is true
}


Here's a breakdown of the steps:

  1. Initialize: Set the initial value for a loop variable.
  2. Condition: Evaluate a condition to determine if the loop should continue or stop.
  3. Increment: Modify the loop variable's value after each iteration.


The continue statement is typically used within conditional statements to skip the remaining code within the current iteration and move on to the next iteration.


Here's an example:

1
2
3
4
5
6
7
for ($i = 1; $i <= 10; $i++) {
    if ($i % 2 == 0) {
        continue;
    }

    echo $i . " ";
}


In this example, the loop iterates from 1 to 10. The if statement checks if the value of $i is divisible by 2 without any remainder. If the condition is true, the continue statement is executed, which skips the remaining code within the current iteration. If the condition is false, the code after the if statement is executed, which prints the value of $i followed by a space.


The output of this example would be:

1
1 3 5 7 9


As you can see, the continue statement skips printing even numbers in this example.