PHP Switch

The switch statement in PHP is used to execute different blocks of code based on the value of an expression. This makes it an efficient alternative to using multiple if...else statements, especially when comparing one expression against multiple cases.

Tutorials dojo strip

Syntax

PHP

How It Works

  1. The expression is evaluated once.
  2. Its value is compared with each case label.
  3. If a match is found, the corresponding block of code is executed.
  4. The break keyword exits the switch block to prevent the execution of the next cases.
  5. If no match is found, the default block runs, if specified.

Example: Choosing a Motorcycle Brand

Here’s an example where a user specifies their preferred motorcycle brand. The program outputs a message based on the choice:

PHP

The break Keyword

The break keyword stops further case evaluations once a match is found. Without it, subsequent case blocks are executed even if they don’t match the expression.

Example: Omitting break

If we remove the break in one of the cases, here’s what happens:

PHP

Here, if the preferredBrand is “Kawasaki”, both the “Kawasaki” and “Ducati” blocks will execute, producing unintended behavior.

The default Keyword

The default block executes when no case matches the expression. While it’s often the last block, it can be placed elsewhere (not recommended) but must include a break to avoid unintended results.

Example: Handling Unmatched Cases

PHP

Common Code Blocks

If multiple cases should trigger the same block of code, they can be grouped:

Example: Grouping Cases

PHP

Tutorials dojo strip