In PHP, the break statement is used to exit a loop before it completes its normal execution. It is commonly used inside loops such as for, while, do-while, and foreach to stop execution based on a specific condition.
🛠 Syntax of Break Statement
<?php break; // Exits the loop ?>
📝 Example 1: Break in a For Loop
This loop stops when $i equals 3.
<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
break; // Stops the loop when $i is 3
}
echo "Number: $i <br>";
}
?>
📝 Example 2: Break in a While Loop
The loop terminates when $count reaches 4.
<?php
$count = 1;
while ($count <= 10) {
if ($count == 4) {
break;
}
echo "Count: $count <br>";
$count++;
}
?>
📝 Example 3: Break in a Foreach Loop
Stops iterating when the value "Cherry" is found.
<?php
$fruits = array("Apple", "Banana", "Cherry", "Mango");
foreach ($fruits as $fruit) {
if ($fruit == "Cherry") {
break;
}
echo "Fruit: $fruit <br>";
}
?>
🎯 When to Use Break?
- To exit a loop early when a condition is met.
- To optimize performance by stopping unnecessary iterations.
- To prevent infinite loops in certain cases.
📝 Practice Time!
Modify the examples to see how break works in different loop scenarios.