Difference between break and continue in PHP
Just like other programming languages, PHP also have two keywords break and continue to control the loop. These statements are known as jumping statement or flow of transfer in the program. In this section, we will discuss the differences between break and continue in PHP.
The break statement is used inside the loop (for, foreach, while and do-while) and switch case statement. As the break statement encountered inside a loop, it immediately terminated the loop statement and transferred the control to the next statement, followed by a loop to resume the execution. It is also used in the nested loop statement, where it breaks the inner loop first and then proceed to break the outer loop. It is also used in the switch case statement to terminate a particular case's execution in the program.
In the above flow diagram, a break statement is placed inside the loop with a condition. If the condition defined in the loop is true, a break statement is immediately executed to break the execution of the loop and to move the control to the next statement followed by the loop.
The continue statement is used in the middle of for loop, while loop, do-while loop, and the foreach loop. As the continue statement is encountered in a loop, it skips the current iteration of the loop and transfers the control to the beginning of the loop for further execution of the loop. For example, in some situations where we want to skip the program's current statement and then starts the next statement, we use the continue statement.
In the above diagram, a continue statement is used to skip a particular iteration of the loop. It is usually used with a condition inside a loop. If the defined condition is true, the continue statement is executed to skip the iteration. After that, it transfers the control to the beginning of the loop for further execution inside the loop.
Let's understand the program of break statement using for loop in PHP.
As we can see in the above example, for loop is continuously executed the program. When the condition of if statement i==7, the break statement encountered inside the loop and terminates the loop. After that, transfer the control to the next statement followed by for loop to execute the statement.
Let's understand the program of continue statement using for loop in PHP.
As we can see in the above example, for loop start the execution of the loop from 1 to 10. When the statement of if statement i==5, a continue statement enters the loop and skips the execution of current statement. After that, transfer the control to the beginning of the loop for further execution of the loop statement.
Difference between the break and continue statement in PHP