- Instant help with your Php coding problems

PHP switch case statement

The switch case statement is a special format of conditional statements. It can be very useful and makes your code more readable if you need to make a lot of decisions with the if - elseif - else  statement. Besides this, a switch case code snippet can be better to debug, maintain and it can result in a bit faster code. However, it has one disadvantage, that programmers usually forgot about the break statements at the end of each instruction block.

The general code flow can be seen in the flow chart below.

Let's suppose the following example where we use the if-else solution:

$x = 3;
 
if ($x == 0) {
    echo "0";
} elseif ($x == 1) {
    echo "1";
} elseif ($x == 2) {
    echo "2";
} elseif ($x == 3) {
    echo "3";
} elseif ($x == 4) {
    echo "4";
} else {
    echo "Not recognized";
}

In this code, we compare the same variable with many different values using the if statement. However, this is the case where we could use the switch-case control structure as well as this:

$x = 3;
 
switch ($x) {
    case 0:
        echo "0";
        break;
    case 1:
        echo "1";
        break;
    case 2:
        echo "2";
        break;
    case 3:
        echo "3";
        break;
    case 4:
        echo "4";
        break;
}

Although the switch solution doesn't result in a shorter code it is a bit easier to understand. However, you have to take care of the break statements which work as a code block terminator.
This example is not exactly the same as the "if" version as for example in the case of $x=10 this code prints nothing. To solve this we can extend our switch statement.

Extend switch statement with default


To solve the previous problem we can extend our code with a default part. The code in this block works as the else block in the case of the if statement. So the complete switch statement will look like this:

$x = 13;
 
switch ($x) {
    case 0:
        echo "0";
        break;
    case 1:
        echo "1";
        break;
    case 2:
        echo "2";
        break;
    case 3:
        echo "3";
        break;
    case 4:
        echo "4";
        break;
    default:
        echo "Not recognized";
        break;
}

The default case matches anything that wasn't matched by the other cases and should be the last case statement. If you want more information about the switch case statement you can visit the relevant wikipedia site and the official php manual pages.

Share "PHP switch case statement" with your friends