PHP Break and Continue
This article will help you understand PHP break and continue and how they can be implemented to improve performance and optimize code.
PHP break and continue statements helps control program flow. When you use break statement, you can exit a loop instantly, while the continue statement skips certain iterations.
You can use these statements to quickly exit loops or skip certain iterations depending on specific conditions.
PHP Break Statement
Using PHP break statement, you can exit a loop/switch statement immediately.
It is useful to use a break statement when it is needed to stop the execution of a loop or switch statement before all its iterations are complete.
Whenever the break statement is encountered within a loop, it immediately exits the loop and continues execution outside the loop. Similarly, when PHP break statement is encountered inside a switch statement, it exits the switch statement and moves on to the next statement outside of the switch statement.
In the example below, If a is equal to 3, the loop terminates:
Example: 
Example: 
PHP Continue Statement
Example: 
Example: 
Break and Continue with While Loop
We can also use break and continue statements in a while loop.
In the following examples, we will see the use of the break and continue statement in the while loop is the same as used in the for loop/switch statement.
The following example terminates the while loop if $a is equal to 3:
Example: 
Example: 
Example: 
Example: 
Example Explanation
Above example creates an array of flowers called $flower and uses a while loop to iterate through the array.
The variable $a is initialized to 0, and is incremented by 1 during each iteration of the loop.
Inside the loop, an if statement is used to check if the current flower is a “tulip“. If it is, the “continue” statement is executed, which skips over the current iteration of the loop and moves on to the next iteration.
This means that the “tulip” flower will not be printed out.
If the current flower is not a “tulip”, the code proceeds to the next line which uses the “echo” statement to print the name of the current flower on a new line, with an HTML <br> tag. The output of this code would be a list of all the flowers in the $flower array, except for the “tulip” flower.
You now know how to break loops using PHP break and continue statements.