Web20 University

How To Use PHP Switch Case (with lots of examples)

Get up to 65% Off Hosting with FREE SSL & FREE Domains!

* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.

The switch statement in PHP is a powerful control structure that allows you to execute different blocks of code based on the value of a given expression. It is a great alternative to multiple if-else statements, making your code cleaner and more readable. In this comprehensive guide, we will explore how to use the switch case in PHP with plenty of practical examples.

Understanding the Switch Case Syntax

The basic syntax of a switch statement in PHP is as follows:

switch (expression) {
    case value1:
        // Code to be executed if expression equals value1
        break;
    case value2:
        // Code to be executed if expression equals value2
        break;
    // You can have any number of cases
    default:
        // Code to be executed if expression doesn't match any case
}
  • expression: The value that you want to test.
  • case: Represents a possible value of the expression. If the expression matches this value, the associated block of code is executed.
  • break: Ends the execution of the current case. Without a break, the code will continue to execute the next case (known as “fall-through”).
  • default: Optional. This code block is executed if the expression doesn’t match any of the cases.

Example 1: Simple Switch Case

Let’s start with a simple example. Suppose we want to print a message based on the day of the week:

<?php
$day = "Wednesday";

switch ($day) {
    case "Monday":
        echo "It's Monday, back to work!";
        break;
    case "Tuesday":
        echo "It's Tuesday, keep going!";
        break;
    case "Wednesday":
        echo "It's Wednesday, halfway through!";
        break;
    case "Thursday":
        echo "It's Thursday, almost there!";
        break;
    case "Friday":
        echo "It's Friday, the weekend is near!";
        break;
    case "Saturday":
        echo "It's Saturday, time to relax!";
        break;
    case "Sunday":
        echo "It's Sunday, enjoy your rest!";
        break;
    default:
        echo "Invalid day!";
}
?>

Example 2: Using Integers in Switch Case

Switch cases can also be used with integers. Here’s an example where we categorize a number based on its value:

<?php
$number = 15;

switch (true) {
    case ($number < 10):
        echo "The number is less than 10.";
        break;
    case ($number >= 10 && $number < 20):
        echo "The number is between 10 and 19.";
        break;
    case ($number >= 20 && $number < 30):
        echo "The number is between 20 and 29.";
        break;
    default:
        echo "The number is 30 or more.";
}
?>

Example 3: Switch Case with Strings and Fall-through

Sometimes, you might want to execute the same block of code for multiple cases. This is where fall-through comes in handy:

<?php
$fruit = "apple";

switch ($fruit) {
    case "apple":
    case "banana":
    case "cherry":
        echo "The fruit is either apple, banana, or cherry.";
        break;
    case "orange":
    case "lemon":
        echo "The fruit is either orange or lemon.";
        break;
    default:
        echo "Unknown fruit.";
}
?>

Example 4: Switch Case with Function Calls

You can call functions within switch cases to keep your code modular and clean:

<?php
function greet() {
    return "Hello!";
}

function farewell() {
    return "Goodbye!";
}

$action = "greet";

switch ($action) {
    case "greet":
        echo greet();
        break;
    case "farewell":
        echo farewell();
        break;
    default:
        echo "No action specified.";
}
?>

Example 5: Nested Switch Case

You can also nest switch cases to handle more complex logic:

<?php
$category = "fruit";
$item = "apple";

switch ($category) {
    case "fruit":
        switch ($item) {
            case "apple":
                echo "It's an apple.";
                break;
            case "banana":
                echo "It's a banana.";
                break;
            default:
                echo "Unknown fruit.";
        }
        break;
    case "vegetable":
        switch ($item) {
            case "carrot":
                echo "It's a carrot.";
                break;
            case "broccoli":
                echo "It's broccoli.";
                break;
            default:
                echo "Unknown vegetable.";
        }
        break;
    default:
        echo "Unknown category.";
}
?>

Best Practices for Using Switch Case in PHP

  1. Use Break Statements: Always use break statements to avoid fall-through unless it’s intentional.
  2. Default Case: Always include a default case to handle unexpected values.
  3. Avoid Complex Expressions: Keep the expressions in the case statements simple to enhance readability.
  4. Consistent Formatting: Maintain consistent formatting and indentation for better readability.

Conclusion

The switch case statement in PHP is a versatile control structure that simplifies decision-making in your code. It provides a clean and efficient way to execute different code blocks based on the value of an expression. By mastering the use of switch cases, you can write more readable and maintainable PHP code.

This guide has covered the basics and provided practical examples to get you started. Experiment with different scenarios and see how switch cases can improve your PHP projects.

Get up to 65% Off Hosting with FREE SSL & FREE Domains!