In this tutorial, we are going to learn about PHP break statement and continue and those importances.
PHP break statement :
A break statement is useful when we want to exit from a loop without completing the iteration.
The keyword break is used universally to get out of loops in PHP. It works for the for, foreach, switch statements, and while statements.
<?php
$apples = array(100, 200, 1100, 300, 600);
$v1 = 0;
$sum = 0;
while ($v1 <= 5) {
if ($sum > 1400) {
break;
}
$sum = $sum + $apples[$v1];
$v1 = $v1 + 1;
}
echo $sum;
?>
Output:
1700
On the above example, the break statement is executed when ever the $sum value is greater then 1400.
PHP Continue Statement :
This statement is used when the developer directs control to the beginning of a loop, effectively skipping other statements inside the loop.
The keyword continue is used. It is also associated with the if statements.
<?php
$x = 1;
echo 'even numbers upto 10<br />';
while ($x <= 10) {
if ($x % 2) {
$x++;
continue;
} else {
echo $x . '<br />';
$x++;
}
}
Output:
even numbers upto 10
2
4
6
8
10
Happy Learning 🙂