PHP Switch Statement Explained: Syntax, Examples, and Everything You Need to Know

PHP switch statement is like a traffic police who decides where to send the traffic (code execution) depending on the signal (value). Instead of writing many if…else if…else, we can use switch for cleaner code.

PHP Switch Statement Explained

Syntax:

<?php

switch (variable) {
    case value1:
        // Code runs if variable == value1
        break;

    case value2:
        // Code runs if variable == value2
        break;

    default:
        // Code runs if no case matched
}


?>

Example (Easy to understand)

Imagine you enter a canteen and ask for food based on a number:

<?php
<?php
$choice = 2;

switch ($choice) {
    case 1:
        echo "You selected Pizza ";
        break;

    case 2:
        echo "You selected Burger ";
        break;

    case 3:
        echo "You selected Pasta ";
        break;

    default:
        echo "Invalid choice, please select again ";
}
?>

?>

Output: You selected Burger

Important Points

  1. break; is used to stop execution after a case matches.
    If you miss break;, PHP will continue to the next case (called fall-through).
  2. default works like else in if-else.
  3. Useful when checking one variable with many possible values.

Quick Real-Life Analogy

Think of switch like a menu card in a restaurant:

  • If you order 1 → Pizza
  • If you order 2 → Burger
  • If you order 3 → Pasta
  • Anything else → “Sorry, not available”