Back to course

The switch Statement

PHP: The Complete 0 to Hero Bootcamp

12. The switch Statement

When you need to test a single variable against many different possible values, the switch statement is cleaner and often more efficient than long chains of elseif.

Basic Switch Structure

The switch statement evaluates an expression once and then compares the result to the values of successive case clauses.

php

The Importance of break

  • The break statement exits the entire switch structure.
  • If you omit break, execution will 'fall through' to the next case, executing its code as well, regardless of whether the next case matches the expression.

The default Case

The default block is optional and executes if none of the case values match the expression.