HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP Break


The break statement is used to exit a loop prematurely and transfer control to the statement immediately following the loop..



Break in For loop

The break statement used in a for loop serves the purpose of immediately terminating the loop's execution as soon as the statement is encountered. .


Example


Jump out of the loop when $x is 4:

<!DOCTYPE html>
<html>
<body>

<?php  
for ($x = 0; $x < 10; $x++) {
  if ($x == 4) {
    break;
  }
  echo "The number is: $x 
"; } ?> </body> </html>

Output

The number is: 0
The number is: 1
The number is: 2
The number is: 3


• Break in While Loop

The break statement in a while loop is used to immediately terminate the loop's execution before the loop condition is re-evaluated for the next iteration.

Example


<!DOCTYPE html>
<html>
<body>

<?php  
$x = 0;
 
while($x < 10) {
  if ($x == 4) {
    break;
  }
  echo "The number is: $x 
"; $x++; } ?> </body> </html>

Output

The number is: 0
The number is: 1
The number is: 2
The number is: 3

• Break in Do While Loop

The break statementin a while loop is used to immediately terminate the loop's execution before the loop condition is re-evaluated for the next iteration.

Example


Stop the loop when $i is 3:

<!DOCTYPE html>
<html>
<body>

<?php  
$i = 1;

do {
  if ($i == 3) break;
  echo $i;
  $i++;
} while ($i < 6);
?>  

</body>
</html>

Output

12

• Break in For Each Loop

The break statement can be used to jump out of a foreach loop.

Example


Stop the loop if $x is "blue":

<!DOCTYPE html>
<html>
<body>

<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $x) {
  if ($x == "blue") break;
  echo "$x 
"; } ?> </body> </html>

Output

red
green