- A break statement can be used to terminate or to come out from the loop or conditional statement unconditionally.
- It can be used in switch statement to break and come out from the switch statement after each case expression.
- Whenever, break statement is encounter within the program then it will break the current loop or block.
- A break statement is normally used with if statement.
- When certain condition becomes true to terminate the loop then break statement can be used.
- The following program demonstrates the use of break statement. Loop will be terminated as soon as the counter value becomes greater than 5.
for( $i = 1; $i <= 10 ; $i++ )
if ($i > 5)
break; // terminate loop
echo "$i"."</br>" ;
- break can also be used with an optional numeric argument to specify how many nested enclosing structures are to be broken out of.
- The default value is 1, means only the immediate enclosing structure is broken out of.
/* Using optional argument. */
$i = 0;
echo "case 5 \n" ;
break 1; /* Exit only the switch. */
echo "case 10; quitting \n" ;
break 2; /* Exit the switch and the while. */
- A continue statement can be used into the loop when we want to skip some statement to be executed and continue the execution of above statement based on some specific condition.
- Similar to break statement, continue is also used with if statement.
- When compiler encounters continue, statements after continue are skipped and control transfers to the statement above continue.
- The following example uses the continue statement to print upper and lower a to z alphabets
/* program to print upper and lower a to z alphabets using continue */
for ( $i = 65 ; $i <= 122 ; $i++ ) // loop through ASCII value for a to z
if($i >= 91 && $i <= 96)
continue ; // skip unnecessary special characters.
echo "| $i "."</br>" ; // print character equivalent for ASCII value.
- Similar to break, continue also accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip.
- The default value is 1, which will skip to the end of the current loop.
$i = 0 ;
while ($i++ < 5)
echo "Outer while\n" ;
echo "Middle while\n" ;
echo "Inner while\n" ;
echo "This will never output.\n" ;
echo "Not even this.\n" ;
- An exit statement is used to terminate the current execution flow.
- As soon as exit statement is found, it will terminate the program.
- It can be used to output a message and terminate the current script: for example exit(“Good Bye!”);
- It can also be used with error code. For example: exit(1), exit(0376).
- the following program demonstrates the use of exit statements.
$filename = 'sample.txt' ;
$file = fopen($filename, 'r') // open file for reading
or exit("unable to open file ($filename)");