Categories
PHP

PHP switch

switch on php.net

An interesting alternative to if/elseif/else in php I came upon. Why use it? After reading around for a bit it would appear its just more human readable. Some say it may be faster in some scenarios, it may be less code, use it if you have more than 3 conditions said another. Heres a thread about it.

Important thing is the ‘break‘ following any matching case, otherwise the code will continue on to the next line. This could be wanted in some situations. Also switch/case does loose comparison.

In the example below the ‘default’ command of ‘echo “Shit ain’t right bro!”; ‘ would fire since no case was set for 79. If $duh was set to 12 then ‘case 12:‘ would run and because a break; follows the command it would end the script, remove that break; and the script continues in order below.

$duh = 79;

switch ($duh) {
    case 12: echo "It is 12";
    break;
    case 73: echo "It is 73";
    break;
    default: echo "Shit ain't right bro!";
}

/* notice no break is needed after the 'default:'
command is used and it is last */

It’s possible to use ‘continue’ in a switch tree.

So ‘case 12:‘ is similar to ‘if ($duh == 12)‘, if is way more flexible and what Id use most times, but I might switch one day 🙂

Another example below with comparison operators, even a strict exact one using === since switch is by default loose comparison.

$a = 8;
switch ($a) {
    case ($a <= 8):
        echo '$a is true';
        break;
    case ($a === false):
        echo '$a is false';
        break;
    case ($a === "blah":
        echo '$a is 0';
        break;
}

/* output would be first case echoing '$a is true'.
Warning of mixing integer and string comparisons, example
change $a = "blah"; then you would get same result and
the script would break after first case even though it
would appear incorrect */

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 12 = 17