Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

PHP Break


PHP break statement breaks the execution of current for, while, do-while, switch and for-each loop. If you use break inside inner loop, it breaks the execution of inner loop only.

Syntax

  1. jump statement;
  2. break;

Flowchart

break

PHP Break: inside loop

Let’s see a simple example to break the execution of for loop if value of i is equal to 5.

  1. <?php
  2. for($i=1;$i<=10;$i++){
  3. echo “$i <br/>”;
  4. if($i==5){
  5. break;
  6. }
  7. }
  8. ?>

Output:

1
2
3
4
5

PHP Break: inside inner loop

The PHP break statement breaks the execution of inner loop only.

  1. <?php
  2. for($i=1;$i<=3;$i++){
  3.  for($j=1;$j<=3;$j++){
  4.   echo “$i   $j<br/>”;
  5.   if($i==2 && $j==2){
  6.    break;
  7.   }
  8.  }
  9. }
  10. ?>

Output:

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

PHP Break: inside switch statement

The PHP break statement breaks the flow of switch case also.

  1. <?php
  2. $num=200;
  3. switch($num){
  4. case 100:
  5. echo(“number is equals to 100”);
  6. break;
  7. case 200:
  8. echo(“number is equal to 200”);
  9. break;
  10. case 50:
  11. echo(“number is equal to 300”);
  12. break;
  13. default:
  14. echo(“number is not equal to 100, 200 or 500”);
  15. }
  16. ?>

Output:

number is equal to 200

Comments

comments