CopyPastehas never been so tasty!

Uses of break statement in PHP

by anonymous

  • 0
  • 0
  • 0
69 views

orignal source:http://codingvilla.com/uses-break-statement-php-single-article-578.aspx

Break Keyword:

 

Break is a keyword used to terminate a loop at any point where you want to finish a loop.It is used to stop the execution of loop like for loop, do-while, case statement etc.

 

Break in PHP:

 

To stop or terminate a loop execution we use break keyword in php. It is a built in keyword in php used to get out of running loops. We can use it in for loop, do-while, switch statement.

 

Break statement in different loops:

 

Break in for each loop:

 

Break statement is used in for each loop to terminate the loop. For Example, to calculate the sum of array values we will insert condition if sum is greater than 300 break else sum the values.

 

 

Code:

 

 

<?php

$amounts = array(45, 18, 73, 154, 90);

$sum = 0;

foreach ($amounts as $value) {

if (($sum+$value) > 300) {

break;

} else {

$sum = $sum + $value;

}

}

echo 'Sum is '.$sum; // Would print Sum is 290

?>

 

Break in while loop:

 

In order to use break in while loop we make increment in variable i that is initialized with zero if i is equal to 3 terminate the loop by using break statement otherwise increment the variable i.

 

 

Code:

 

 

<?php

  $i = 0;

  while ( $i < 6 )

  {

    if( $i == 3) break;

    $i++;

  }

  echo("Loop stopped at $i by break statement");

?>

 

Break in switch statement:

 

In order to use break in switch statement we first initialized a variable with value 50 now code finds case where value is 50 when found display a message and terminate.

 

Code:

 

<?php

$value = 50;

switch ($value) {

case 50:.

echo 'Value is 50 <br />';

break;

case 70:

echo 'Value is 70 <br />';

break;

case 90:

echo 'Value is 90 <br />';

break;

}

?>

 

 

Above is a simple code to use break statement in php.

 

This simple article tells that how we can use break statement in php.

Add A Comment: