PHP break Statement

PHPServer Side ProgrammingProgramming

Introduction

The break statement is one of the looping control keywords in PHP. When program flow comes across break inside while, do while, for as well as foreach loop or a switch construct, remaining statements in the loop/swtich is abandoned and statements after the same will be executed.

Syntax

while (expr)
{
   ..
   ..
   if (expr1)
   break;
   ..
   ..
}

In following example, the while loop continues to read user input till a string END is entered.

Example

<?php
while (TRUE){
   $var=readline("enter something (END to stop loop)");
   if ($var=="END")
      break;
   echo "You entered $var\n";
}
?>

Output

This will produce following result −

enter something (END to stop loop)Hello
You entered Hello
enter something (END to stop loop)PHP
You entered PHP
enter something (END to stop loop)END

The keyword continue can have an optional numeric argument to specify how many levels of inne loops are to be skipped. Default is 1

In case of nested loop, break will abandon current loop only. In following example, break statement has been use in inner loop.

Example

 Live Demo

<?php
for ($i = 1;$i<=5;$i++) {
   echo "Start Of outer loop\n";
   for ($j=1;$j<=5;$j++) {
      if ($j >=3) break ;
         echo "I : $i J : $j"."\n";
   }
   echo "End of inner loop\n";
}
?>

Output

This will produce following result −

Start Of outer loop
I : 1 J : 1
I : 1 J : 2
End of inner loop
Start Of outer loop
I : 2 J : 1
I : 2 J : 2
End of inner loop
Start Of outer loop
I : 3 J : 1
I : 3 J : 2
End of inner loop
Start Of outer loop
I : 4 J : 1
I : 4 J : 2
End of inner loop
Start Of outer loop
I : 5 J : 1
I : 5 J : 2
End of inner loop

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. In following example break 2 inside innder loop breaks out of outer loop as well

Example

 Live Demo

<?php
for ($i = 1;$i<=5;$i++) {
   echo "Start Of outer loop\n";
   for ($j=1;$j<=5;$j++) {
      if ($j >3) break 2 ;
      echo "I : $i J : $j"."\n";
   }
   echo "End of inner loop\n";
}
?>

Output

This will produce following result −

I : 1 J : 1
I : 1 J : 2
I : 1 J : 3

In a switch construct, break prevents program from falling through when desired value of switching variable is obtained.

Example

<?php
$x=25;
$var=(int)readline("enter a number 1 for square 2 for square root: ");
switch($var){
   case 1:echo sqrt($x). "\n";
      break;
   case 2:echo pow($x, $var) . "\n";
}
?>

Output

This will produce following result −

enter a number 1 for square 2 for square root: 2
625
enter a number 1 for square 2 for square root: 1
5
raja
Published on 19-Sep-2020 12:42:39
Advertisements