PHP Break Statement

To control the flow of code execution JavaScript provides break and continue statements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively. These statement provides full control to handle loops and switch statements.

The break is special statement that can be used inside the loops. It terminates the current loop and execution control transfer after the end of loop. The basic syntax :
 break;
Where the break keyword terminates the current loop.
 while() {
   break;
 }
For example :
<?php
  $x = 1;
  while($x <= 10) {
    echo $x . "<br/>";
    $x++;
    if($x == 6) {
      break;
    }
  }
?>
Output :

1
2
3
4
5

The above code will break the while loop when $x is equal to 6.  The break statement is mostly used in nested loops to break the inner loops. For example :
<?php
  for($x = 1; $x <= 3; $x++) {
    for($y = 1; $y <= 3; $y++) {
      if($x == 2 && $y == 2) {
        break;
      }
      echo "$x : $y<br/>";
    }
  }
?>
Output :

1 : 1
1 : 2
1 : 3
2 : 1
3 : 1
3 : 2
3 : 3

The Break statement is also used within the switch() statement.
<?php
  $gander = "Male";

  switch($gander) {
    case "Male":
      echo "You are a Male.";
      break;
    case "Female":
      echo "You are a Female.";
      break;
    default:
      echo "Gander not specified";
      break;
  }
?>
Output :

You are a Male.


Next Topic :