PHP - Switch

  »   PHP  »   PHP Tutorial - Switch

The PHP switch statement (native function) executes a different piece of code depending on the value of a variable (or expression).

Here is a simplified version of the PHP switch syntax:

PHPswitch (expression) {
    case value_1:
        // case expression = value_1
        break;

    case value_2:
        // case expression = value_2
        break;

    case value_3:
        // case expression = value_3
        break;
    ...

    default:
        // default code to be executed if none of the above cases are met
}

PHP switch example

The switch statement is quite simple. It evaluates the expression or variable once, and then it compares the value to one of the given cases. If no match is found, then the default case is executed. Use break after every block of code to prevent code form continuing.

Here is a real example of using the PHP switch statemented

PHP<?php
$role = "editor";

switch ($role) {
    case "admin":
        echo "Hello master. You can manage users and edit their content.";
        break;

    case "editor":
         echo "As an editor, your job is very important to us. You can manage your profile and create, edit and publish your own content.";
        break;

    case "customer":
         echo "Thank you for registering. You have now access to all our content. Enjoy reading";
        break;

    default:
         echo "Your are an anonymous visitor. Please register to have access to cool stuff";
}
?>

This will simply print the following line

PHPAs an editor, your job is very important to us. You can manage your profile and create, edit and publish your own content.

There are times when you want to execute the same block of code for multiple cases. This is how you group case for the PHP switch statement.

PHP<?php
$role = " publisher_team ";

switch ($role) {
    case "administration_geek":
    case "moderation_board":
    case "marketing_department":
        echo "Case administrator, moderator and marketing";
        break;

    case "editor_stuff":
    case "publisher_team":
         echo "Case editor and publisher";
        break;

    case "paying_customers":
    case "registered_users":
         echo "Case customer and users";
        break;

    default:
         echo "Undefined role will execute this code";
}
?>

This will simply print the following line

PHPCase editor and publisher

The PHP switch alternative syntax

There is no switch shorthand like the if statement for example but there is instead an alternative for the above syntax.

PHP<?php
$role = "editor";

switch ($role):
    case "admin":
        echo "I am the one that knows your browser history";
        break;

    case "editor":
        echo "I edit stuff";
        break;

    case "customer":
        echo "I both things";
        break;

    default:
        echo "Nobody is perfect. I am nobody";

endswitch;
?>

On the PHP manual page there is a notice that you can not insert a space or line-break between the "switch ($role):" and "case "admin":". This will trigger a warning

PHPParse error: syntax error, unexpected T_INLINE_HTML, expecting T_ENDSWITCH or T_CASE or T_DEFAULT

In other words this will not be correct:

PHP<div>
<?php switch($role): ?>
    <?php case "admin": ?>
        <div>This switch syntax is not correct</div>
        <?php break;?>
    <?php case "editor": ?>
        </div>This way of using switch will trow a syntax error<div>
        <?php break;?>
<?php endswitch;?>
</div>

Although this PHP switch code seems perfectly valid, there is a line-break after this . Remember that when you close the PHP code, The HTML comes in, and that line-break is interpreted as a "\r\n" or carriage return.

Mixing statements

Although for some it may seem obvious, I would like to mention that, like any other statement, you can mix the switch statement with any other statements. For example, you can place a second switch inside it, an if, a do-while or any other complex piece of code. On the other hand is not always a good idea place to much code inside a switch statement. It is a good practice to stay simple and use a separate function or build an object if you have to place a lot of code inside a switch.

PHP<?php
$role       = "administration";
$action     = true;
$came_from  = "home_page";

switch ($role) {
    case "administration":
        if($action): 
            # do some cool things
        else:
            # do some other awesome things
        endif;

        break;

    case "paying_customers":
    case "registered_users":
         say_hello();
        break;

    default:
        
        # Undefined role will execute this code
        switch ($came_from) {
            case "home_page":
                echo "You think our home page is cool?";
                break;

            case "article_page":
                echo "Did you liked the previous article?";
                break;

            default:
            # if none of the above, it means it comes from organic search 
            echo "Hmm...Is this what you were looking for in the first place?";
        }
}

/*
 * This function will get all user info from database (for example)
 */
function say_hello(){
    echo "Hi there $name!!";
    # a lot of code here
}

?>

Take a closer look to the above switch syntax and try to understand it. It is a good idea to practice a little bit before continuing to the next tutorial. See you on the next page.