W3docs

How to Use Continue and Break in PHP

The continue and break keywords are used to control the whole program flow. This snippet will show you examples of how to use these keywords in PHP.

The <kbd class="highlighted">continue</kbd> and <kbd class="highlighted">break</kbd> keywords are used to control the flow inside loops and switch statements.

The <kbd class="highlighted">continue</kbd> keyword skips the current iteration, while <kbd class="highlighted">break</kbd> exits the loop entirely.

This snippet will demonstrate some examples of how to use these keywords correctly.

Using the continue Keyword Inside a Loop

Here, you will see an example of using the <kbd class="highlighted">continue</kbd> keyword inside a loop:

php use continue inside a loop

<?php

for ($i = 1; $i < 10; $i++) {
  if ($i % 2 == 0) {
    continue;
  }
  echo $i . " ";
}

?>

1 3 5 7 9

Using break Inside a Loop

Now, let’s see how to use the <kbd class="highlighted">break</kbd> keyword inside a loop:

php use break keyword inside a loop

<?php

for ($i = 1; $i < 10; $i++) {
  if ($i == 5) {
    break;
  }
  echo $i . " ";
}

?>

1 2 3 4

Using a switch in a Loop

In this section, we will use a <kbd class="highlighted">switch</kbd> inside a loop with continue 2 within the case of the switch.

Here is an example:

php use switch in a loop

<?php

for ($i = 10; $i <= 15; $i++) {
  switch ($i) {
    case 10:
      echo "Ten";
      break;

    case 11:
      continue 2;

    case 12:
      echo "Twelve";
      break;

    case 13:
      echo "Thirteen";
      break;

    case 14:
      continue 2;

    case 15:
      echo "Fifteen";
      break;
  }

  echo "<br> Below switch, and i = " . $i . ' <br><br> ';
}

?>

Ten
Below switch, and i = 10 
Twelve
Below switch, and i = 12 
Thirteen
Below switch, and i = 13 
Fifteen
Below switch, and i = 15

The Differences Between continue and break

To have a better understanding of how to use these keywords in PHP, you need to know the differences between them.

Here, we will outline the three main differences between <kbd class="highlighted">continue</kbd> and <kbd class="highlighted">break</kbd>:

  1. continue always skips the current iteration, whereas break terminates the entire loop.
  2. break exits the loop early, while continue simply proceeds to the next iteration.
  3. Inside a loop containing a switch statement, break terminates the current case, while continue 2 skips the current case and moves to the next loop iteration.