Difference Between exit and break in PHP

This article is created to differentiate exit() and break in PHP.

The PHP exit() terminates the execution of the current PHP script, whereas the break terminates the execution of the current loop or switch structure. For example, let me use break first:

<?php
   for($i=1; $i<10; $i++)
   {
      if($i==4)
         break;
      echo "The value of \$i is $i";
      echo "<BR>";
   }
   echo "<HR>";
   echo "Some text right after the 'for' loop...";
   echo "<BR>";
   echo "Some other text...";
?>

The output of this PHP example is:

php exit vs break

And let me create the same example, using exit():

<?php
   for($i=1; $i<10; $i++)
   {
      if($i==4)
         exit();
      echo "The value of \$i is $i";
      echo "<BR>";
   }
   echo "<HR>";
   echo "Some text right after the 'for' loop...";
   echo "<BR>";
   echo "Some other text...";
?>

Now the output is:

php break vs exit

That is, the break is used when we need to exit from a loop, whereas the exit is used when we need to exit from the whole PHP script/program.

PHP Online Test


« Previous Tutorial Next Tutorial »