PHP Keywords: switch, case, default and endswitch

16 February 2019 - 5:28am

Welcome to my series on every PHP keyword and its usage. Today's items: switch, case, default and endswitch.

A switch is used to handle situations where you have a lot of different conditional branches for a single variable. Instead of using a large number of elseif statements, it's often cleaner to use a switch.

Cases in a switch statement are denoted with the case keyword, and typically completed using the break keyword. However, return or exit statements negate the need to explicitly break the case.

A final special case is the default case, which works the same way as the else clause in an if statement; a condition that is only triggered if none of the other cases are met.

In PHP, a switch has two forms, one using curly braces, and the other using the endswitch keyword.

Usage

Curly braces

<?php
$colour = "red";

switch($colour)
{
    case "red":
        $flower = "roses";
    break;

    case "blue":
        $flower = "violets";
    break;

    default:
        $flower = "unknown";
    break;
}

endswitch

Note: This usage seems to be aimed mostly at templates, so I would encourage you not to use it outside of templating. If you're looking to avoid spaghetti code entirely, you may want to look into Twig, which is a popular templating engine that encourages you to separate behaviour from presentation.

<?php
$colour = "red";

switch($colour):
    case "red":
        $flower = "roses";
    break;

    case "blue":
        $flower = "violets";
    break;

    default:
        $flower = "unknown";
    break;
endswitch;