How to Use Continue and Break in PHP
The continue and break keywords are used to control the whole program flow. This snippet will show you examples of how to use these keywords in PHP.
The <kbd class="highlighted">continue</kbd> and <kbd class="highlighted">break</kbd> keywords are used to control the flow inside loops and switch statements.
The <kbd class="highlighted">continue</kbd> keyword skips the current iteration, while <kbd class="highlighted">break</kbd> exits the loop entirely.
This snippet will demonstrate some examples of how to use these keywords correctly.
Using the continue Keyword Inside a Loop
Here, you will see an example of using the <kbd class="highlighted">continue</kbd> keyword inside a loop:
php use continue inside a loop
<?php
for ($i = 1; $i < 10; $i++) {
if ($i % 2 == 0) {
continue;
}
echo $i . " ";
}
?>1 3 5 7 9Using break Inside a Loop
Now, let’s see how to use the <kbd class="highlighted">break</kbd> keyword inside a loop:
php use break keyword inside a loop
<?php
for ($i = 1; $i < 10; $i++) {
if ($i == 5) {
break;
}
echo $i . " ";
}
?>1 2 3 4Using a switch in a Loop
In this section, we will use a <kbd class="highlighted">switch</kbd> inside a loop with continue 2 within the case of the switch.
Here is an example:
php use switch in a loop
<?php
for ($i = 10; $i <= 15; $i++) {
switch ($i) {
case 10:
echo "Ten";
break;
case 11:
continue 2;
case 12:
echo "Twelve";
break;
case 13:
echo "Thirteen";
break;
case 14:
continue 2;
case 15:
echo "Fifteen";
break;
}
echo "<br> Below switch, and i = " . $i . ' <br><br> ';
}
?>Ten
Below switch, and i = 10
Twelve
Below switch, and i = 12
Thirteen
Below switch, and i = 13
Fifteen
Below switch, and i = 15The Differences Between continue and break
To have a better understanding of how to use these keywords in PHP, you need to know the differences between them.
Here, we will outline the three main differences between <kbd class="highlighted">continue</kbd> and <kbd class="highlighted">break</kbd>:
continuealways skips the current iteration, whereasbreakterminates the entire loop.breakexits the loop early, whilecontinuesimply proceeds to the next iteration.- Inside a loop containing a
switchstatement,breakterminates the current case, whilecontinue 2skips the current case and moves to the next loop iteration.