PHP Break statement
The break
statement can be used to jump out of different kind of loops.
Break in For loop
The break
statement can be used to jump out of a for
loop.
Example
Jump out of the loop when $x
is 4
:
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
Break in While Loop
The break
statement can be used to jump out of a while
loop.
Break Example
$x = 0;
while($x < 10) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
$x++;
}
Break in Do While Loop
The break
statement can be used to jump out of a do...while
loop.
Example
Stop the loop when $i
is 3:
$i = 1;
do {
if ($i == 3) break;
echo $i;
$i++;
} while ($i < 6);
Break in For Each Loop
The break
statement can be used to jump out of a foreach
loop.
Example
Stop the loop if $x
is "blue":
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
if ($x == "blue") break;
echo "$x <br>";
}
PHP Continue statement
The continue
statement can be used to jump out of the current iteration of a loop, and continue with the next.
Continue in For Loops
The continue
statement stops the current iteration in the for
loop and continue with the next.
Example
Move to next iteration if $x
= 4:
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
Continue in While Loop
The continue
statement stops the current iteration in the while
loop and continue with the next.
Continue Example
Move to next iteration if $x
= 4:
$x = 0;
while($x < 10) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
$x++;
}
Continue in Do While Loop
The continue
statement stops the current iteration in the do...while
loop and continue with the next.
Example
Stop, and jump to the next iteration if $i
is 3:
$i = 0;
do {
$i++;
if ($i == 3) continue;
echo $i;
} while ($i < 6);
Continue in For Each Loop
The continue
statement stops the current iteration in the foreach
loop and continue with the next.
Example
Stop, and jump to the next iteration if $x
is "blue":
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
if ($x == "blue") continue;
echo "$x <br>";
}