Case switching

Consider this piece of code:

    $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:

    $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 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's 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.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Loops >>

Previous chapter: Conditional statements

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.