Home Blog break and continue Keywords in PhP

break and continue Keywords in PhP

0
break and continue Keywords in PhP

The break statement

The PHP break keyword is used to terminate the execution of a loop prematurely.

The break statement is situated inside the statement block. It gives you full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed.

In the following example condition test becomes true when the counter value reaches 3 and loop terminates

<?php
 $i = 0;
         
  while( $i < 10) {
  $i++;
  if( $i == 3 )break;
  }
  echo ("Loop stopped at i = $i" );
?>

Output: Loop stopped at i = 3

The continue statement

The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.

Just like the break statement the continue statement is situated inside the statement block containing the code that the loop executes, preceded by a conditional test. For the pass encountering continue statement, rest of the loop code is skipped and next pass starts.

In the following example loop prints the value of array but for which condition becomes true it just skip the code and next value is printed.

<?php
  $array = array( 1, 2, 3, 4, 5);
       
  foreach( $array as $value ) {
  if( $value == 3 )continue;
  echo "Value is $value <br />";
  }
?>

Output:
Value is 1
Value is 2
Value is 4
Value is 5

LEAVE A REPLY

Please enter your comment!
Please enter your name here