PHP Break

The break statement is particularly useful when you need to stop loop execution based on a condition, preventing unnecessary iterations.


Using break in a for Loop


The break statement can be used to jump out of a for loop.



Example
<!DOCTYPE html>
<html>
<body>
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break; // Exits the loop when $i equals 5
}
echo "Number: $i<br>";
}
?>
</body>
</html>

Try it yourself

Using break in a while Loop


The break statement can be used to jump out of a while loop.

Example
<!DOCTYPE html>
<html>
<body>
<?php
$x = 1;

while ($x <= 10) {
echo "Value: $x<br>";
if ($x == 4) {
break; // Exit the loop when $x is 4
}
$x++;
}
?>
</body>
</html>

Try it yourself

Using break in a do...while Loop


The break statement can be used to jump out of a do...while loop.

Example
<!DOCTYPE html>
<html>
<body>
<?php
$i = 1;

do {
if ($i == 3) break;
echo $i;
$i++;
} while ($i < 6);
?>
</body>
</html>

Try it yourself

Using break in a foreach Loop


The break statement can be used to jump out of a foreach loop.

Example
<!DOCTYPE html>
<html>
<body>
<?php
$colors = ["red", "green", "blue", "yellow"];

foreach ($colors as $color) {
if ($color == "blue") {
break; // Stops the loop when $color is "blue"
}
echo "Color: $color<br>";
}
?>
</body>
</html>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.