PHP ยท Chapter 16 of 44

PHP Break & Continue

The break statement immediately ends the loop (or switch) it is inside, jumping to the code right after it. The continue statement skips the rest of the current iteration and moves on to the next one.

Both keywords give you finer control over loop execution, letting you exit early when a condition is met or skip specific items without processing the entire loop body.

Syntax
break;
continue;

Using break

break is often used to stop a loop as soon as a certain value is found, avoiding unnecessary further iterations once the goal has been reached.

Using continue

continue is useful for skipping items that don't need processing, such as skipping even numbers while summing only odd numbers.

Example 1 (php)
<?php
  for ($i = 1; $i <= 10; $i++) {
    if ($i == 4) {
      break;
    }
    echo $i . " ";
  }
?>
Output
1 2 3 

The loop stops completely as soon as $i equals 4.

Example 2 (php)
<?php
  for ($i = 1; $i <= 5; $i++) {
    if ($i % 2 == 0) {
      continue;
    }
    echo $i . " ";
  }
?>
Output
1 3 5 

continue skips printing whenever $i is even, moving straight to the next iteration.

Key points

  • break exits the loop entirely.
  • continue skips only the current iteration.
  • Both can be used in while, do-while, for and foreach loops.
  • break also exits a switch statement's current case.
๐Ÿ’ก Note: Overusing break and continue can make loop logic harder to follow โ€” use them sparingly and clearly.

๐Ÿ“ Quick Quiz

1. What does break do inside a loop?

2. What does continue do?

3. Can break be used inside a switch statement?