PHP switch Statement [With Examples]

PHP switch Statement

As you get more confident with your PHP code, your code will get more and more complex. The PHP switch statement simplifies your PHP logic, replacing messy if statements when trying to make simple decisions based on the value of a variable. Read on to find out how to use it.

PHP switch Syntax

switch($v) {
    case $a:
        # Code to be executed if  $v is equal to $a
        break;
    case $b:
        # Code to be executed if  $v is equal to $b
        break;
    case $c:
        # Code to be executed if  $v is equal to $c
        break;
    ...
    default;
        # Default code to be executed if no condition met
}

Note that:

  • The switch statement is followed by the variable or value to compare
  • The case statements inside the switch block are followed by the second variable or value to compare
    • The code following the colon in the case statement will only execute if the switch and case values match
  • Only one default case is allowed, which will execute if no break statement exists prior
    • The break statement prevents any following cases from being tested, thus preventing their code from running
    • The continue statement can be used in place of break
    • continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip – see later in the article for what this means in switch statements
  • switch/case makes a loose comparison by default
    • This means that 2 and “2” are equal – as are 0 and FALSE – as the variable type is ignored
    • See later in the article on how to use strict comparisons where the variable type are considered

switch Examples

Consider the following series of if/elseif statements that print information about a number:

if ($var == 0) {
    echo "$var equals 0";
} elseif ($var == 1) {
    echo "$var equals 1";
} elseif ($var == 2) {
    echo "$var equals 2";
} else [
    echo "i is not equal to 0, 1, or 2";
]

Here is the same functionality, but using a switch statement instead:

switch ($var) {
    case 0:
        echo "$var equals 0";
        break;
    case 1:
        echo "$var equals 1";
        break;
    case 2:
        echo "$var equals 2";
        break;
    default:
        echo "i is not equal to 0, 1, or 2";
}

This is a lot easier to write and is also a lot easier to read.

The break statement can be left out of a case, if you wish to continue making further comparisons:

switch ($var) {
    case 0:
    case 1:
        echo "$var equals 0 or 1";
        break;
    case 2:
        echo "$var equals 2";
        break;
    default:
        echo "i is not equal to 0, 1, or 2";
}

Above, if $var is equal to 0 or 1, the case statement will be executed for all unbroken cases above it.

Variable Types

As mentioned earlier, switch/case does a loose comparison by default.

There is a trick to get around this – testing whether all cases are truthy, and making all cases a boolean expression that performs strict comparisons:

$var = 0;

switch (true) {
    case ($var === true):
        echo '$var is true';
        break;
    case ($var === false):
        echo '$var is false';
        break;
    case ($var === 0):
        echo '$var is 0';
        break;
}

Only the last case above will run, as strict comparisons will not evaluate 0 as false. The case comparison will succeed as the bracketed condition will evaluate to true and match the switch statement’s value.

This can also be used to supply comparisons that check for things other than equality as cases, such as greater than or less than:

$var = 0;

switch (true) {
    case ($var < 1):
        echo '$var is less than 1';
        break;
    case ($var > 1):
        echo '$var is greater than 1';
        break;
}

Using continue instead of break

If you are using a switch statement in a loop, you can use the continue statement instead of break to end the actions in the switch statement, as well as skipping to the next iteration in the loop it is contained within.

This is done by providing a numeric argument to continue to tell it how many levels of enclosing loops should be skipped – and it counts the switch statement as a loop for this purpose. For example:

$array = [1, 2, 3];

foreach($array as $vartem) {

    switch($vartem) {
        case 1:
            echo 'a'; 
            continue 2;
        case 2:
            echo 'b'; 
            continue 2;
        default:
            echo 'c'; 
            continue 2;
    }

    echo 'x';
}

… will output:

abcx

As the continue 2 statements are skipping the remaining cases in the switch statement as well as the foreach loop they are contained in.

Click here to view the official PHP documentation for the switch statement and Check out our other PHP programming articles!

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

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