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:
forloopswhileloopsdo...whileloopsforeachloops
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:
php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
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:
php
$x = 0;
while($x < 10) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
$x++;
}
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:
php
$i = 1;
do {
if ($i == 3) break;
echo $i;
$i++;
} while ($i < 6);
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":
php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
if ($value == "blue") break;
echo "$value<br>";
}