It’s Festive Season! Enjoy 30% Off

Use code FESTIVE30 at checkout

Code has been added to clipboard!

PHP switch case Statement: Learn Syntax and Understand the Use

Reading time 2 min
Published Aug 8, 2017
Updated Sep 24, 2019

We have learned how PHP if statement works. Now, we're going to get familiar with the PHP switch case statement. They both are considered conditional statements that allow developers to prepare portions of code for different results.

By using the switch PHP statement, developers can specify blocks of code to be run in different cases. Let's review the syntax rules and a code example to better grasp how to use the PHP switch case statement correctly.

PHP switch case: Main Tips

  • This statement is used to execute different blocks of code for different cases.
  • The default case matches anything that wasn't matched by the other PHP switch cases specified.
  • Such statement structure allows the usage of strings.

Statement Syntax

When developers need to use switch PHP statement, they have to make sure they follow syntax rules. View the scheme below. You can clearly see which block of code needs to be executed in each PHP switch case. For your convenience, we provide a detailed explanation so that even beginners would be able to understand:

switch (x) {
case name1:
code to be run if x=name1;
break;
case name2:
code to be run if x=name2;
break;
case name3:
code to be run if x=name3;
break;
...
default:
code to be run if x doesn't match any names specified;
}

Practice: Code Example

Memorizing the syntax rules is one thing. It is also important to understand how this statement works. Let's break down how exactly PHP switch statement performs in an example below.

First, a single expression (the x in our syntax scheme) gets evaluated once. It is usually a variable: in our example below, it is called $car and represents a major car manufacturer. Its value is then compared to the values of every separate case in the structure.

After a match is found, the block of code inside that PHP case is executed. break is used to stop the code from automatically running further on. The last statement in the example is default: the code below it is executed if no PHP case match is found:

Example
<?php
  $car = "bmw";

  switch ($car) {
    case "bmw":
      echo "Your favorite car is bmw!";
      break;
    case "audi":
      echo "Your favorite car is audi!";
      break;
    case "subaru":
      echo "Your favorite car is subaru!";
      break;
    default:
      echo "Your favorite car is neither bmw, audi, nor subaru!";
  }
?>

PHP switch case: Summary

  • When you need to run different blocks of code for different cases, PHP switch statement comes in handy.
  • The default case steps in when the cases developer has specified don't return any matches.
  • Data strings can be used with the PHP switch.