How to use the continue statement in PHP?

Member

by larissa , in category: PHP General , 7 months ago

How to use the continue statement in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 6 months 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.