Switch in PHP

Switch statements express conditionals across many branches.

Here’s a basic switch in PHP.

<?php
$i = 2;
echo "Write $i as ";
switch ($i) {
    case 1:
        echo "one\n";
        break;
    case 2:
        echo "two\n";
        break;
    case 3:
        echo "three\n";
        break;
}
?>

You can use commas to separate multiple expressions in the same case statement. We use the optional default case in this example as well.

<?php
$day = date('l');
switch ($day) {
    case 'Saturday':
    case 'Sunday':
        echo "It's the weekend\n";
        break;
    default:
        echo "It's a weekday\n";
}
?>

switch without an expression is an alternate way to express if/else logic. Here we also show how the case expressions can be non-constants.

<?php
$hour = date('H');
switch (true) {
    case ($hour < 12):
        echo "It's before noon\n";
        break;
    default:
        echo "It's after noon\n";
}
?>

A type switch in PHP is done by checking the type using functions like is_bool, is_int, etc. This is how we can discover the type of a variable.

<?php
function whatAmI($i) {
    switch (true) {
        case is_bool($i):
            echo "I'm a bool\n";
            break;
        case is_int($i):
            echo "I'm an int\n";
            break;
        default:
            echo "Don't know type " . gettype($i) . "\n";
    }
}

whatAmI(true);
whatAmI(1);
whatAmI("hey");
?>

To run the translations above, save each code snippet into a .php file and run them using php from the command line.

$ php switch_basic.php
Write 2 as two
$ php switch_weekday.php
It's a weekday
$ php switch_before_noon.php
It's after noon
$ php switch_type.php
I'm a bool
I'm an int
Don't know type string

Next example: Arrays.