Break and Continue- PHP statements to Interrupt or Skip Loops

When using the PHP looping constructs, you may need to interrupt a loop when a specific condition becomes true. For example, if you may wish to print first 10 students studying a subject in a given list of students. You add a counter variable in the loop checking subject of each student. As soon as this counter becomes 10 you wish to terminate the loop. In another case you may want to skip certain statements within a loop block on occurrence of a condition. Both these requirements can be fulfilled with PHP statements – Break and Continue.

Break Statement

PHP Break statement gives you the flexibility to break a loop whenever you need without executing remaining iterations. Suppose you have defined a loop that must run 10 times, but on 5th iteration a condition occurs when you have to terminate your loop. All you need to do is add the break statement with this condition specified with if conditional construct. After 5th iteration the loop will break and the next statement after loop will execute. The rest of 5 iterations will not execute.

Example- display first 5 even numbers in give list using while loop

 <?php
$numArray= array(2,3,6,7,9,11,2,88,5,3,20,43,5,66,8,222,132);
$ctr=0;
$count=0;
while ( $ctr<count($numArray))
{
               if ($numArray[$ctr]%2==0)
                {
                echo "$ctr values is $numArray[$ctr]<br>";
                $count++;
                }
                if ($count==5)
                                                break;
                $ctr++;
}
echo "These are the first five even numbers of given list";
?>

Output

PHP break statement

 

In the coding example the loop is terminated with a break statement as soon as the $count variable is 5. It is incremented each time an even number is encountered in the array $numArray.

Continue Statement

Continue statement is the opposite of Break Statement. In the loop statements block when a continue is encountered, the control skips the rest of statements and starts again at the header of loop with next iteration. Like Break statement the continue statement have to be associated with a condition using if conditional construct.

Example- display even numbers after 5th element in give list using for loop

 

 <?php
$numArray= array(2,3,6,7,9,11,2,88,5,3,20,43,5,66,8,222,132);

$count=0;
for  ($ctr=0; $ctr<count($numArray);$ctr++)
{
      if ($ctr<5)
      {
            continue;
      }
      if ($numArray[$ctr]%2==0)
            echo "$ctr value is $numArray[$ctr]<br>";
}
echo "These are the even numbers after 5th element of the given list";
?>

Output:

PHP continue statement

In this example the first five iterations will be executed without checking the number for even property. This is done with continue in the loop with condition ($ctr<5). After the fifth iteration each number is checked and printed if it is even.