Skip to main content

The PHP switch Statement

When one value can lead to several different actions, a switch statement keeps them neatly organized. PHP uses it to pick one block of code out of many and run it.

Switch syntax

A switch statement is laid out like this:

index.php
<?php
switch (expression) {
  case label1:
    //code block
    break;
  case label2:
    //code block
    break;
  case label3:
    //code block
    break;
  default:
    //code block
}
?>

How It Works

PHP works out the expression a single time, then compares the result with the value of each case in turn. When it finds a match, it runs the code for that case. Put a break at the end of each block, because without one PHP would carry on into the next case. If nothing matches, the default block runs instead.

Switch statement with colors

Depending on what $favcolor holds, a different message is printed. It is set to "red" here:

Prompt
Write a PHP script that sets a variable $favcolor to "red". Use a switch statement to check the value of $favcolor. If "red", echo "Your favorite color is red!". If "blue", echo "Your favorite color is blue!". If "green", echo "Your favorite color is green!". Add a default case that echoes "Your favorite color is neither red, blue, nor green!".
Output: PHP script

The default Keyword

The default keyword marks the code to use when none of the cases match. Think of it as the else at the end of an if...elseif...else statement.

Switch with day of the week

This switch turns the day number from date("w") into the name of today's day:

Prompt
Write a PHP script that sets a variable $d to the current day number of the week using date("w"). Use a switch statement with cases for each day (0=Sunday through 6=Saturday), echoing the day name. No default case is needed since all seven days are covered.
Output: PHP script

Common Code Blocks

Several cases can share one code block. Stack them directly above each other and leave out the break between them. This technique is sometimes called fall-through.

Fall-through in switch

The "red" and "blue" cases are stacked, so either value leads to the same message:

Prompt
Write a PHP script that sets $favcolor to "red". Create a switch statement where the "red" case does NOT have a break statement, so it falls through to the "blue" case. The "blue" case echoes "Your favorite color is either red or blue!" and breaks.
Output: PHP script