Hudzilla.org - the homepage of Paul Hudson
Contents > Introducing PHP > How PHP is written Wish List | Report Bug | About Me ]

2.6.9     Case switching

This is NOT the latest copy of this book; click here for the latest version.

Consider this piece of code:

<?php
    $Name
= "Bob";
    if (
$Name == "Jim") {
        print
"Your name is Jim\n";
    } else {
        if (
$Name == "Linda") {
            print
"Your name is Linda\n";
        } else {
            if (
$Name == "Bob") {
                print
"Your name is Bob\n";
            } else {
                if (
$Name == "Sally") {
                    print
"Your name is Sally\n";
                } else {
                    print
"I do not know your name!\n";
                }
            }
        }
    }
?>

As you can see, here we're just trying to find out which piece of code we should execute, however it requires a lot of code because of the way if statements work. PHP has a solution to this, and it is called switch/case statements. In a switch/case block you specify what you are checking against, then give a list of possible values you want to handle. Using switch/case statements, we can rewrite the previous mess of if statements like this:

<?php
    $Name
= 'Bob';
    switch(
$Name) {
        case
"Jim": print "Your name is Jim\n"; break;
        case
"Linda": print "Your name is Linda\n"; break;
        case
"Bob": print "Your name is Bob\n"; break;
        case
"Sally": print "Your name is Sally\n"; break;
        default: print
"I do not know your name!\n";
    }
?>

Switch/case statements are used all the time to check all sorts of data, and as you can see they take up much less room than equivalent if statements.

There are two important things to note in the PHP switch/case statement code. Firstly, there is no word "case" before "default" - that is just how the language works.

Secondly, each of our case actions end with "break;". This is because once PHP finds a match in its case list, it will execute the action of that match as well as the actions of all matches beneath it (further down on your screen). This might not seem very helpful at first, but there are many situations where it comes in useful - not the least of which is trying to program a script to print out the song "The 12 Days of Christmas"!

The keyword "break" means "get out of the switch/case statement", and has the effect of stopping PHP from executing the actions of all subsequent cases after its match. Without the break, our test script would print out this:

Your name is Bob
Your name is Sally
I do not know your name

Once PHP matches Bob, it will execute Bob's action, then Sally's, then the default also. It is generally best to use "break" unless you specifically want to have the fall-through behaviour.





<< 2.6.8 Conditional statements   2.6.10 Loops >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
Mike - 05 Dec 2008

@TxtEdMacs: If you got a long if block with multiple else if statements, try using the break statement at the end of each in between the brackets at the end, to stop checking all other values.

Great tutorial. I wish I saw this before I learnt switch, as your explanation via example is great.

A PHP Soopr NOOB - 05 Dec 2008

Which would execute faster...
an if ifelse else,
or a case switch?

Personnaly I have to say this is an excellent tutorial...
Thanx!

A PHP Soopr NOOB - 05 Dec 2008

Which would execute faster...
an if ifelse else,
or a case switch?

Personnaly I have to say this is an excellent tutorial...
Thanx!

A PHP User - 05 Dec 2008

Ganesan Rajagopal is right - this code could look like this:
<?php
$Name = "Bob";
if ($Name == "Jim") print "Your name is Jim\n";
elseif ($Name == "Linda") print "Your name is Linda\n";
elseif ($Name == "Bob") print "Your name is Bob\n";
elseif ($Name == "Sally") print "Your name is Sally\n";
else print "I do not know your name!\n";
?>

i think that author should try a bit harder to find a good expamples ;] (but we all got the point anyway)

TxtEdMacs - 05 Dec 2008

PHP User - thanks for your response. My comment was really more of a complaint about the deficient implementation of the switch/case command compared to what I had used previously (albeit a long time ago). Moreover, until last night, I held the mistaken belief that the implementation in C was more robust. To my shock C and php switch/case works in an identical fashion. I gained my misimpression from an individual that "corrected" my FoxPro code and my incomplete understanding of the actual functioning of that code structure in C.

One more comment, if you check my comment associated with 2.6.8 and you will see I used the if () {...}elseif () {...} else } structure. However, I did not know that all subsequent conditions were checked after the first True. Since the code block was very large I could be taking a significant performance hit. Nonetheless, reflecting a bit more: on my machine it runs rapidly and the way the code is employed that may not be important. Regarding the latter point, the logs are analyzed off line for part of a statistical analysis of site usage.

Thanks again for your comment, I am a bit less ignorant today.

A PHP User - 05 Dec 2008

TxtEdMacs, Your'e looking for if-elseif.... not switch-case


eg:

if($foo == $bar){...}
elseif($foo == upcase($bar)) {...}
elseif{$foo == "help") {...}
else {...}

only here both sides of the test and the condition can be varied not just the right side...

TxtEdMacs - 05 Dec 2008

I wish this switch/case command would come near to matching the FoxPro code I used on DOS and Windows back in the 90's! The necessity of having the case be a specified value kills the utility in too many cases. It was nice too that the FP CASE didn't require the break; as the switch in C.

Hari - 05 Dec 2008

This is a cool way to have explained the case statement. It was simple and straight.

Ganesan Rajagopal - 05 Dec 2008

The nested if statements are a bit unfair. You would normall use a elseif statement for this type of usage. I admit that the nested makes the case statement look a lot more nicer, I think that it's better to let the case statement stand in it's own merit, rather than trying to make the if statement ugly.

effigy - 05 Dec 2008

The switch example can be tidied like so:

<?php
$Name = 'Bob';
switch($Name) {
case "Jim":
case "Linda":
case "Bob":
case "Sally":
print "Your name is $Name\n"; break;
default: print "I do not know your name!\n";
}
?>

Another PHP - 05 Dec 2008

Read Herbert Schildt`s C++ The Complete Reference. It`s more detailed

Shantuk123@lycos.com - 05 Dec 2008

This is an excellent explanation of case statements. Even better than other books and other languages have.



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is one plus four?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow