PHP Break & Continue Control Statements Tutorial
In this tutorial we learn about the break and continue control statements in PHP and how they help us control the flow of our applications in PHP.
What are control statements?
Control statements help us control the flow of execution in our PHP applications. Control statements are commonly used within iteration and conditional control structures we learned about in previous tutorial lessons.
Break control statement
The break control statement will allow us to break out of the intended flow of execution wherever we write the break keyword.
<?php
for ($i=0; $i < 10; $i++) {
if ($i == 5) {
break;
}
echo $i . "<br>";
}
echo "I am outside and after the loop"
?>
In the example above, we tell the interpreter to break out of the loop once the counter reaches 5. The interpreter then continues on to execute the code outside and after the loop.
We saw this control statement used in a switch block in the tutorial lesson on Conditional Control.
The interpreter needs to be told to break out of the switch block when it finds the match, otherwise it will simply continue on to the next case.
<?php
$num = 2;
switch ($num) {
case 1:
echo $num;
case 2:
echo $num;
default:
echo "Default";
}
?>
In the example above, the interpreter does not break out of the switch block when it encounters the match to $num. It simply continues on to the next case, and executes it.
Continue control statement
The continue control statement will tell the interpreter to continue to the next iteration of the loop.
<?php
for ($i=0; $i < 10; $i++) {
if ($i == 5) {
continue;
}
echo $i . "<br>";
}
echo "I am outside and after the loop"
?>
In the example above, we tell the interpreter to continue to the next iteration of the loop once the counter reaches 5, effectively skipping the echo statement that prints the number. The interpreter then continues to execute the loop as it would normally.
Summary: Points to remember
- Control statements are keywords that tell the interpreter to change the flow of our application.
- The break statement will break out of its parent and move on to code outside and below it.
- The continue statement will return execution to its parent.