• Register

Php allows you to control the flow of loops and switch, to accomplish this PHP has a ’ Break ‘and Continue statement. Both the break and continue to have their own importance and priority over each other depending on what you expect from the loop or want to perform some specific actions.  

The main difference between Break and continue Statement is that break terminates all remaining iterations prematurely when specific conditions come true while continue statement will skip an iteration when you condition comes true and continues looping other iterations. We will check both of them one by one based on their functionality and purpose of use.

Break Statement:  

Break statement in PHP is used to terminate all remaining iterations when the desired condition is fulfilled or comes true by loop or switch. For example, you have a loop of 10 iterations and if you achieve your result at the 5th iteration remaining iterations will be killed. This very helpful to reduce code execution time. We will further check this one example.

<html>
<body>
<?php  
for ($i = 0; $i < 10; $i++) {
  if ($i == 5) {
    break;
  }
  echo "The number is: $i <br>";
}
?>
</body>
</html>

In the above program, we have a FOR loop with 10 iterations and we want to break out control when we reach iteration number 5, the loop started and we have output up to  5 iterations, and control was prematurely terminated.

Continue statement:

Continue statement in PHP is used to skip a particular iteration number and continue executing others. Continue statement can be used with for loop, for each loop, and while loop. 

<html>
<body>

<?php  
for ($j= 0; $j < 10; $j++) {
//check for odd number 
  if ($j%2 ==0 ) {
    continue;
  }
  echo "The odd number is: $j <br>";//this will display only odd numbers and skips iterations for even number
}
?>

</body>
</html>

in the above example, we used a continue statement to skip iteration for even numbers and display only odd numbers. It will skip all even iterations and will only show output for odd number of iterations.

4,670 points
9 5 1