PHP Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 3.00

"break" and "continue" Statements

This section describes how 'break' and 'continue' statements works in PHP. 'break' statement breaks the statement block and the loop. 'continue' statement breaks the statement block, but continues on the next iteration of the loop.

In order to help us control the execution flow better, PHP provides two special statements, "break" and "continue", for statement blocks:

1. "break" statement with no option: It breaks the current statement block and the current loop where the "break" statement is located. The remaining statements in the current statement block will not be executed. If current statement block is running as a loop, the loop will also be terminated.

   any_block {
      ...
      any_block {
         ... 
         any_block {
            ...
            break;
            ...
         }
         ...
      }
      ...
   }

2. "break" statement with an option of integer, n: It breaks statement blocks and loops n levels backward. The remaining statements in all n levels of statement blocks will not be executed. If any of those statement blocks are loops, those loops will also be terminated.

   any_block {
      ...
      any_block {
         ... 
         any_block {
            ...
            break n;
            ...
         }
      }
   }

3. "continue" statement with no option: It breaks the current statement block and continues on the next iteration of the current loop where the "continue" statement is located. The remaining statements in the current statement block will not be executed. But the loop will continue on the next iteration, if current statement block is running as a loop.

   any_block {
      ...
      any_block {
         ... 
         any_block {
            ...
            continue;
            ...
         }
         ...
      }
      ...
   }

4. "continue" statement with an option of integer n: It breaks statement blocks and loops n levels backward. The remaining statements in all n levels of statement blocks will not be executed. But the n-th level loop will be continued on the next iteration, if the n-th level statement block is running as a loop.

   any_block {
      ...
      any_block {
         ... 
         any_block {
            ...
            continue n;
            ...
         }
         ...
      }
      ...
   }

I will leave it to you to write some sample scripts for "break" and "continue" statements as exercises.

Last update: 2005.

Sections in This Chapter

"while" Statements

"while" Statement Examples

"for" Statements

"for" Statement Examples

"do ... while" Statements

"break" and "continue" Statements

Dr. Herong Yang, updated in 2009
"break" and "continue" Statements