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

"switch" Statements

This section describes how 'switch' statements work. Execution will start at the 'case' clause whose expected value matches the test expression. Execution will continue with all remaining 'case' clauses.

"switch" statement is an alternative way of executing statements selectively based on certain conditions. Here is the syntax of "switch" statements:

   switch (test_expression) {
      case expected_value_1: 
         statement_block_1;
         break;
      case expected_value_2: 
         statement_block_2;
         break;
      ...
      default:
         last_statement_block;
   }

where "test_expression" is an expression used to test against with expected values specified in "case" clauses, and "expected_value_*" are expected values.

The execution of a "switch" statement goes like this:

  • Each "case" clause will be visited sequentially from top to bottom.
  • If the result of the test expression matches the expected value in a "case" clause, the statement block in that clause will be executed.
  • One a statement block is executed, all remaining statement blocks will also be executed.
  • If no "case" clause is executed, the "default" clause will be executed.
  • To stop executing remaining statements, you can use the "break" statement.

Last update: 2005.

Sections in This Chapter

"if" Statements

"if" Statement Examples

"switch" Statements

"switch" Statement Examples

Dr. Herong Yang, updated in 2009
"switch" Statements