Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Case Switching

Your if...elseif blocks can become unwieldy when you have a series of conditions that all test against the same variable, as here:

    <?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 don't know your name!\n";
            }
    ?>

PHP has a solution to this: switch/case. 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 script 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 don't know your name!\n";
            }
    ?>

Switch/case statements are frequently used to check all sorts of data, and they take up much less room than equivalent if statements.

There are two important things to note in the PHP switch/case statement code. First, there is no word "case" before "default"—that is just how the language works. Second, each of our case actions above 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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page