PHP Break

PHP break statement stop the execution of the current Control loop Statement like for, while, do-while, switch, and for each loop.

If you use break statement inside inner loop body, it breaks the execution of inner loop only.

The break statement can be used to jump out of a loop. PHP break control statement breaks current execution of the loop and php programming control start execution at next statements outside the loop.

PHP Syntax:

break;

PHP Break inside for loop

PHP Code Example 1:
Look at below php code.  If variable $i value is 3 inside for loop,  then it stops the execution of for loop and php control start execution after for loop.
<?php
        for($i=0;$i<=8;$i++) {
          if ($i==3) {
            break;
          }
          echo "The number is: $i <br>";
        }

       echo "Welcome to aryatechno! <br>";
 ?>
Output:
The number is: 0
The number is: 1
The number is: 2
Welcome to aryatechno!

PHP Break inside switch statement
The PHP break statement stops execution at inside case 60: in switch loop.
PHP Code Example 2:
<?php        
    $marks=60;        
    switch($marks){        
        case 50:        
            echo("marks is 50");        
            break;        
        case 60:        
            echo("marks is 60");        
            break;        
        case 70:        
            echo("marks is 70");        
            break;        
        default:        
            echo("marks is not valid!!");        
    }       
    ?> 

Output:
marks is 60

PHP Break inside foreach loop

Execution is stopped when color is white in below example.

PHP Code Example 3:
<?php  
        $color = array("red", "orange", "white", "blue", "yellow");  
        foreach($color as $key=>$value) {  
            if ($value=="white") {  
                break;  
            }  
            echo "color is $value </br>";  
        }  
    ?> 

Output:
color is red
color is orange

PHP Break inside while loop

PHP Code Example 4:

<?php
    $num=1;
    while($num <= 8) {
      if ($num==4) {  
                break;  
      }    
      echo "The number is: $num <br>";
      $num++;
    }
?>
Output:
The number is: 1
The number is: 2
The number is: 3

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

83453