Home PHP What is break and continue statements in PHP loops?

What is break and continue statements in PHP loops?

Author

Date

Category

In PHP, the break and continue statements are used within loops to alter the flow of execution. Here’s an explanation of how break and continue work in PHP:

  1. break statement:
    The break statement is used to exit a loop prematurely. When encountered, the break statement terminates the execution of the innermost loop (whether it’s a for, while, do-while, or foreach loop) and continues execution with the next statement after the loop.

Example of using break:

for ($i = 0; $i < 5; $i++) {
    if ($i == 3) {
        break; // Exit the loop when $i equals 3
    }
    echo $i . ' ';
}
PHP


Output:

0 1 2
PHP


In this example, the loop iterates from 0 to 4. When $i is equal to 3, the break statement is encountered, and the loop is immediately terminated. The value of $i is never echoed when it’s 3.

  1. continue statement:
    The continue statement is used to skip the current iteration of a loop and move to the next iteration. When encountered, the continue statement jumps to the next iteration, without executing the remaining code within the loop for that particular iteration.

Example of using continue:

for ($i = 0; $i < 5; $i++) {
    if ($i == 2) {
        continue; // Skip the current iteration when $i equals 2
    }
    echo $i . ' ';
}
PHP


Output:

0 1 3 4
PHP


In this example, the loop iterates from 0 to 4. When $i is equal to 2, the continue statement is encountered. As a result, the code within the loop for that iteration is skipped, and the loop proceeds to the next iteration.

Both break and continue statements provide control over the execution flow within loops, allowing you to selectively exit the loop or skip specific iterations based on certain conditions.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subhash Shipu

PHP Expert

Hey there! I'm a PHP geek on a mission to blog my way through the coding chaos. When I'm not chasing semicolons, I'm busy cuddling my pet Coco, who thinks debugging means chasing her own tail. Join the fun!

Subscribe

Recent posts