0
0
PhpHow-ToBeginner · 3 min read

How to Use Switch Case in PHP: Syntax and Examples

In PHP, use the switch statement to select one of many code blocks to execute based on a variable's value. Each case defines a value to match, and break stops further checks. Use default to run code if no cases match.
📐

Syntax

The switch statement evaluates an expression and compares it to multiple case values. When a match is found, the code inside that case runs until a break is encountered, which stops the switch. The default case runs if no other case matches.

  • switch(expression): The value to check.
  • case value: A possible match.
  • break: Stops checking further cases.
  • default: Runs if no case matches.
php
switch (expression) {
    case value1:
        // code to run if expression == value1
        break;
    case value2:
        // code to run if expression == value2
        break;
    default:
        // code to run if no case matches
        break;
}
💻

Example

This example shows how to use switch to print a message based on a variable's value.

php
<?php
$day = "Tuesday";
switch ($day) {
    case "Monday":
        echo "Start of the work week.";
        break;
    case "Tuesday":
        echo "Second day of the work week.";
        break;
    case "Friday":
        echo "Last workday!";
        break;
    default:
        echo "It's a weekend or a holiday.";
        break;
}
?>
Output
Second day of the work week.
⚠️

Common Pitfalls

Common mistakes include forgetting break statements, which causes "fall-through" where multiple cases run unintentionally. Also, using loose comparison can cause unexpected matches. Always use break unless you want multiple cases to run.

php
<?php
// Wrong: missing break causes fall-through
$color = "red";
switch ($color) {
    case "red":
        echo "Color is red.";
    case "blue":
        echo "Color is blue.";
        break;
}

// Right: break stops fall-through
switch ($color) {
    case "red":
        echo "Color is red.";
        break;
    case "blue":
        echo "Color is blue.";
        break;
}
?>
Output
Color is red.Color is blue.
📊

Quick Reference

KeywordDescription
switchStarts the switch statement with an expression to check
caseDefines a value to compare with the expression
breakStops execution inside the switch to prevent fall-through
defaultRuns if no case matches the expression

Key Takeaways

Use switch to select code blocks based on a variable's value.
Always include break to avoid running multiple cases unintentionally.
Use default to handle unmatched cases.
Each case compares with strict equality (===) in PHP 8.0+.
Switch statements improve readability over many if-else checks.