Break and continue in PHP

In this tutorial you will learn how to break a loop (stop a loop from running when a certain condition is met) and continue (skip an iteration of a loop). A for loop will be used for the example shown in this tutorial.

There may be situations where you may wish to use the break statement if you want a loop to stop running if a condition from an if statement inside the loop evaluates to true. Similarly, you may also want to skip an iteration of a loop using the continue statement.

Watch the video below and then scroll down to see the examples of break and continue being used in PHP code.

Sample PHP code for breaking a loop:

1
2
3
4
5
6
7
8
<?php
 for($i=0; $i<10; $i++){
 if($i==8){
 break;
 }
 echo $i , '</br>';
 }
?>

Sample code for using continue to skip an iteration of a loop:

1
2
3
4
5
6
7
8
<?php
 for($i=0;$i<10;$i++){
 if($i==5){
 continue;
 }
 echo $i , '</br>';
 }
?>

Sample code for using continue to skip any even numbers in a for loop:

1
2
3
4
5
6
7
8
<?php
 for($i=0;$i<10;$i++){
 if($i%2==0){
 continue;
 }
 echo $i , '</br>';
 }
?>

Sample code for using continue to skip any odd numbers in a for loop:

1
2
3
4
5
6
7
8
<?php
 for($i=0;$i<10;$i++){
 if($i%2!=0){
 continue;
 }
 echo $i , '</br>';
 }
?>

PHP Manual references: