PHP Break statement

The PHP break statement is used to end a loop prematurely by inserting the break keyword inside a conditional statement. As the interpreter finds the break, it terminates the loop, and execution is passed to code next to the current loop. The break statement works for all the PHP loops, i.e., Do..while, while, for loop, foreach loop, etc.

Example of using break inside foreach loop.

			

<?php
$planets = ["Mercury", "Venus", "Earth","Mars"];
foreach($planets as $planet) {
  echo $planet . "<br>";
  if($planet == " Earth ") {
    break;
  }
}
?>

				

Output:

Mercury Venus Earth

Example of using break inside while loop.

			

$count = 0;
while ( true ) {
 $count++;
 echo “I ’ ve counted to: $count < br / > ”;
 if ( $count == 10 ) break;
}

				

Another common reason to break out of a loop is that the purpose you want to achieve has been fulfilled, and now you want to exit from the loop prematurely.

Example:

			

$randnum = rand( 1, 100 );
for ( $x=1; $x < = 100; $xi++ ) {
 if ( $x == $randnum ) {
 	echo “ The random number was: $x < br / > ”;
 	break;
 }
}

				

The code uses PHP ’s rand() function to generate and store a random integer between 1 and 100, then loops from 1 to 100 to find the previously held number. It displays the message once the number is found, and the loop is terminated with the break keyword. Without a break, the loop will execute until the end and take more time.

While using the break statement with nested loops, an optional numeric argument can be passed to mention a number of levels of nesting to break out of. For example:

			

// Break out of the inner loop when $subjets  == 3
for ( $students = 0; $students < 50; $students ++ ) {
 for ( $subjects = 0; $subjects< 8; $subjects ++ ) {
 if ( $subjects == 3 ) break 1;
 echo $students . $subjects . “ < br / > ”;
 }
}

				
			

// Break out of the outer loop when $subjets  == 3
for ( $students = 0; $students < 8; $students ++ ) {
 for ( $subjects = 0; $subjects< 10; $subjects ++ ) {
 if ( $subjects == 3 ) break 2;
 echo $students . $subjects . “ < br / > ”;
 }
}