Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Break and Continue in PHP

Introduction

In PHP, control structures allow you to control the flow of the program. Two important control structures are break and continue. These are used within loops to alter the normal flow of the loop.

The break Statement

The break statement is used to exit from a loop before it has finished executing all its iterations. This can be useful if you want to stop the loop based on a certain condition.

Example of using break:

<?php
for ($i = 0; $i < 10; $i++) {
    if ($i == 5) {
        break;
    }
    echo $i . " ";
}
?>
                    
Output: 0 1 2 3 4

In the above example, the loop will terminate when $i equals 5, even though the loop’s condition allows it to run up to 9.

The continue Statement

The continue statement is used to skip the current iteration of a loop and proceed to the next iteration. This can be useful if you want to skip certain iterations based on a condition.

Example of using continue:

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

In the above example, the iteration when $i equals 5 is skipped, and the loop continues with the next iteration.

Using break and continue in Nested Loops

Both break and continue can be used in nested loops. You can also specify an optional numeric argument to determine how many levels of enclosing loops should be terminated or skipped.

Example of using break in nested loops:

<?php
for ($i = 0; $i < 3; $i++) {
    for ($j = 0; $j < 3; $j++) {
        if ($j == 1) {
            break 2;
        }
        echo "i=$i, j=$j\n";
    }
}
?>
                    
Output: i=0, j=0

In this example, the break 2 statement terminates two levels of loops, hence exiting both the inner and outer loops when $j equals 1.

Example of using continue in nested loops:

<?php
for ($i = 0; $i < 3; $i++) {
    for ($j = 0; $j < 3; $j++) {
        if ($j == 1) {
            continue 2;
        }
        echo "i=$i, j=$j\n";
    }
}
?>
                    
Output: i=0, j=0 i=1, j=0 i=2, j=0

In this example, the continue 2 statement skips the current iteration of the outer loop when $j equals 1, effectively continuing with the next iteration of the outer loop.

Conclusion

Understanding how to use break and continue statements effectively can help you control the flow of loops in PHP more precisely. The break statement is used to terminate the loop, while the continue statement is used to skip the current iteration and proceed to the next one.