How to Use Continue and Break in PHP

The continue and break keywords are used to control the whole program flow.

Both of them are handy for skipping the loop iteration.

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

Watch a course Learn object oriented PHP

Using the continue Keyword Inside a Loop

Here, you will see an example of using the continue keyword 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 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 switch inside a loop with continue 2 within the case of the switch.

Here is an example:

<?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 perception 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 continue and break:

  1. Continue always skips the current iteration whereas break is capable of terminating the whole iteration of the loop.
  2. Break is capable of terminating the whole loop early, while continue brings early merely the next iteration.
  3. Inside a switch loop, break is a terminator for a case, while continue 2 terminates both for a case and skips the current iteration of the loop.