DEV Community

loading...
Cover image for Difference between break and continue in PHP

Difference between break and continue in PHP

joshuabrown0010 profile image joshua-brown0010 ・1 min read

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>
Enter fullscreen mode Exit fullscreen mode

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.
Read more

Discussion (0)

pic
Editor guide