Control Structures


break

break ends execution of the current for, while, do-while or switch structure.

Syntax Description
for( ; ; )
{
  if(expr)
  {
    stmt;
    break;
  }
}
executes stmt and exit iteration and
get out of for loop if expr is TRUE
<?php
  for($i = 0; ; $i++)  // infinite loop
  {
    if($i > 10)
      break;           // exit for loop
    echo $i;
  }
?>
[result]  
012345678910
  • Option of break
    break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.
<?php
  $j = 1;
  for($i = 0; ; $i++)  // infinite loop(level 1)
  {
    while($j != 0)     // infinite loop(level 2)
    {
      if($j > 10)
        break 2;       // exit for loop as well as while loop
      echo $j;
      $j++;
    }
  }
?>
[result]  
12345678910