Course Content
About Lesson

Switch Statement in PHP

The switch statement is used when we have many possible conditions to check, and we want a cleaner way than writing multiple if...elseif...else.

switch (variable) {
    case value1:
        // Code to execute if variable == value1
        break;
    case value2:
        // Code to execute if variable == value2
        break;
    case value3:
        // Code to execute if variable == value3
        break;
    default:
        // Code to execute if no case matches
}
  • switch checks a variable/expression against multiple case values.
  • If a match is found, that block of code runs.
  • break is used to stop execution of the switch.
  • If no match is found, the default block runs.
PHP
<?php
$day = "Tuesday";

switch ($day) {
    case "Monday":
        echo "Today is Monday.";
        break;
    case "Tuesday":
        echo "Today is Tuesday.";
        break;
    case "Wednesday":
        echo "Today is Wednesday.";
        break;
    default:
        echo "Not a valid day.";
}
?>
  • $day = "Tuesday"
  • Switch checks each case.
  • Matches Tuesday, so output: Today is Tuesday.
  • break prevents checking the rest.

You can combine multiple cases to perform the same action.

PHP
<?php
$day = "Saturday";

switch ($day) {
    case "Saturday":
    case "Sunday":
        echo "It's the weekend!";
        break;
    default:
        echo "It's a weekday.";
}
?>
  • If $day is Saturday or Sunday → Output: It's the weekend!
  • Else → It's a weekday.

You can combine multiple cases to perform the same action.

PHP
<!DOCTYPE html>
<html>
<head>
    <title>Switch Example</title>
</head>
<body>
    <form method="post">
        Enter a number (1-3): <input type="number" name="num">
        <button type="submit">Check</button>
    </form>

    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $num = $_POST['num'];

        switch ($num) {
            case 1:
                echo "You selected One.";
                break;
            case 2:
                echo "You selected Two.";
                break;
            case 3:
                echo "You selected Three.";
                break;
            default:
                echo "Invalid choice.";
        }
    }
    ?>
</body>
</html>
if-elseifswitch
Can check complex conditions (>, <, &&,
Good for ranges and logical conditionsGood for exact matches
Slightly harder to read with many conditionsCleaner and easier with multiple values