PHP Break Statement
The PHP Break Statement
The PHP break
statement is used to immediately break out of different kind of loops.
The break statement ends the execution
of the entire loop.
The break statement is used in:
-
forloops -
whileloops -
do...whileloops -
foreachloops
PHP break Out of For loop
The break statement can be used to
immediately break out of a
for loop.
Example
Break out of the loop when $x is 4:
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
Try it Yourself »
PHP break Out of While Loop
The break statement can be used to
immediately break out of a
while loop.
Example
Break out of the loop when $x is 4:
$x = 0;
while($x < 10) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
$x++;
}
Try it Yourself »
PHP break Out of Do While Loop
The break statement can be used to
immediately break out of a
do...while loop.
Example
Break out of the loop when $i is 3:
$i = 1;
do {
if ($i == 3) break;
echo $i;
$i++;
} while ($i < 6);
Try it Yourself »
PHP break Out of Foreach Loop
The break statement can be used to
immediately break out of a
foreach loop.
Example
Break out of the loop if $value is "blue":
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
if ($value == "blue") break;
echo "$value<br>";
}
Try it Yourself »