The PHP Switch Statement

The PHP switch statement is a good substitute for a lot of "if, "else", and "elseif" statements. The switch statement is much more efficient than the "if", "elseif" statements, however there are some quirks that you should be aware of in using switch. This article came when I wanted to do an "or" condition in one of the case tags. As usual, it took me awhile to find what I wanted. I thought it would help if I put all the quirks in one article.

First, lets look at the basic switch statement.

include "chk.php";
$var = 0;
new chk($var);
SwitchDemo($var);
function SwitchDemo($var)
{
  switch ($var) 
  {
    case 0:
		echo "Hello";
		break;
    case 1: 
	        echo " World!";
		break;
    case 2:
	        echo "The real McCoy";
	        break;
    case 3:
                echo "Went too far";
	        break;
    case 4 :
		if ($type == "string" ) {
                    $myarray = array_push($buildarr, $type);
                    break;
                }
		break;
    default:
	    echo "went way too far";
	    break;
	}
}

Here's the code we'll use initially to test things out. A word of explanation. Include "chk.php" is my free variable checking class that you can read about and download here. To use the class, I simply say "new chk($var);". The output is in the picture below. The output says $var is an integer set to "0" that was called in my test script file, "switch.php", on line 21. The output of the switch statement is "Hello".

This is a standard switch statement that we'll start with so you can quickly refer to the syntax when needed. The switch statement executes a different section of code depending on which case is true. The switch variable to be checked should be in parenthesis, and each case tag ends with a ":", a colon, although if you messed up and used a semicolon, I think you'll find that it still works. I'll let you test that out on your own. Note the brackets surrounding all the case and default tags. Also, notice in Case 4, you can have a fairly complex series of commands in the case block, not just one or two lines. We'll leave Case 4 out in the rest of this article just to keep things simple.

The first thing to know is the switch statement does a "loose" comparison between the value in the switch parenthesis and the case value, as opposed to a strict comparison. This would be like using a == in an if statement, instead of a ===. Let's just say that switch does a pretty good job, and if there's any doubt, re-do the variable to make sure there's no ambiguity, that can mean, just making the comparison all integers. If your using integers to compare, you do not need quotes around the integers as shown in our first example. With strings, put quotes around the string.

OK, lets move on. The default case is used, if none of the other case statements are true. A little known fact is the case statements, and the default statement, don't need to be in any sort of order. Let's move the default up, change the case statements around, and change our variable to 2 to better show this. Here's the code scrambled. I'll cut down the code to show just the switch statement. The other code is still running.

	switch ($var) 
	{
	    case 3:
              echo "Went too far";
	      break;
	    default:
	      echo "went way too far";
	      break;
            case 1: 
	      echo "World!";
              break;
	case 0:
   	      echo "Hello";
	      break;	
    case 2:
	    echo "The real McCoy";
	    break;

And here's the output:

Next, we want to talk about "break" and "continue". "break;" breaks you out of the switch statement all together. You're done your filtering, and you're moving on. "continue;" means move to the next case block. Let's show this, we'll put the switch back in order and use a continue.


switch ($var) 
{
    case 0:
		echo "Hello";
		continue;
    case 1: 
	    echo "World!";
		break;
    case 2:
	    echo "The real McCoy";
	    break;
    case 3:
        echo "Went too far";
	    break;
    default:
	    echo "went way too far";
	    break;
}

Here's the output:

I know you were expecting "Hello World", lol. No, even though we are "continuing" to match case blocks, we still have to match. Which brings me to why I wrote the article: How can I output "Hello World!" ?

We'll use a not well known feature of the switch, the "fall through" in the switch statement. If we take out the continue, and leave the break on case 1, we'll get close to our desired results. Here's the code:

switch ($var) 
{
    case 0:
	    echo "Hello";
    case 1: 
	    echo " World!";
		break;
    case 2:
	    echo "The real McCoy";
	    break;
    case 3:
            echo "Went too far";
	    break;
    default:
	    echo "went way too far";
	    break;
}

Here's the output:

In this case, there was no break for Case 0, so when the $var was 0, it outputs "Hello World!" It fell through to Case 1. What happens if we set the $var to 1. Here's the output.

Here we did not match the "0", so "Hello" did not output, and because the HTML tags were not correct the CSS styling did not load, and make "World!" bigger. Let's fix this and make the switch statement really useful. Here's the code:

switch ($var) 
{
    case 7:
    case 8:
    case 0:
    case 1: 
	    echo "Hello World!";
		break;
    case 2:
	    echo "The real McCoy";
	    break;
    case 3:
        echo "Went too far";
	    break;
    default:
	    echo "went way too far";
	    break;
	}

Here's the output:

Woo horsey! What's going on here? We put in a variable of 8 and we get "Hello World!" What happen is the case block matched the 8 and fell through to case 1 and out came "Hello World!". We then broke out of the switch statement. What this means to you is that you can use "OR" conditions with the switch statement.

Instead of:


if( $var == 7 || $var == 8 || $var == 0 || $var == 1) {

}

We can use our switch statement above, which seems a lot easier to me, and more important less prone to syntax errors when we have "OR" statements.

One last thing, we can use calculations in our matches. Let do a final example. Here we'll go back to all the code, and use more than one variable. Here's the code:


include "chk.php";
$var1 = 1;
$var4 = 4;
new chk($var1, $var4);

SwitchDemo($var1, $var4);
function SwitchDemo($var1, $var4)
{
switch ($var1 + $var4) 
{
    case 7:
    case 8:
    case 0:
    case 1: 
	    echo "Hello World!";
	    break;
    case (2 + 3):
	    echo "The real McCoy";
	    break;
    case 3:
            echo "Went too far";
	    break;
    default:
	    echo "went way too far";
	    break;
	}
}

Here's the output:

Here we used calculations, a simple add, in both the switch parameter statement and the case parameter, and we get "The real McCoy." This is equivalent to:

 
if( $var1 && $var2)  {

} 

We've used switch to add variables, and check for an "AND" condition. You can use this to concatenate strings, if you like. You can see the versatility of the switch statement.

In conclusion, the switch statement is more efficient than the "elseif" type of statement. The interpreter makes a list of case comparisons, and then goes right to the case that matches instead of checking every comparison one at a time. Hopefully, you won't shy away from using the switch statement in the future now that you know all the ins and outs. Chow, until next time.

Comments are closed.