PHP Break & Continue

PHP Break & Continue Statements – Control Loop Execution

In PHP, the break and continue statements allow you to control the flow of loops. The break statement immediately exits a loop, while the continue statement skips the current iteration and proceeds to the next one.

🔹 PHP Break Statement

The break statement is used to terminate a loop when a certain condition is met.

📝 Example 1: Using Break in a For Loop

Here, the loop stops when $i equals 3.

<?php
for ($i = 1; $i <= 5; $i++) {
    if ($i == 3) {
        break; // Exits the loop when $i is 3
    }
    echo "Number: $i <br>";
}
?>
    

Try It Now

📝 Example 2: Using Break in a While Loop

The loop stops completely when $count reaches 4.

<?php
$count = 0;
while ($count < 6) {
    $count++;
    if ($count == 4) {
        break; // Stops loop when $count is 4
    }
    echo "Count: $count <br>";
}
?>
    

Try It Now

🔹 PHP Continue Statement

The continue statement skips the current iteration and moves to the next one.

📝 Example 3: Using Continue in a For Loop

Here, the loop skips number 3 but continues execution.

<?php
for ($i = 1; $i <= 5; $i++) {
    if ($i == 3) {
        continue; // Skips iteration when $i is 3
    }
    echo "Number: $i <br>";
}
?>
    

Try It Now

📝 Example 4: Using Continue in a Foreach Loop

Skips "Cherry" while iterating through the array.

<?php
$fruits = array("Apple", "Banana", "Cherry", "Mango");

foreach ($fruits as $fruit) {
    if ($fruit == "Cherry") {
        continue; // Skips "Cherry"
    }
    echo "Fruit: $fruit <br>";
}
?>
    

Try It Now

🎯 Key Differences Between Break & Continue

  • break → Completely stops the loop.
  • continue → Skips the current iteration and moves to the next one.

📝 Practice Time!

Modify the examples and experiment with different values to understand how break and continue work!