PHP switch

Description

To test an expression against a range of different values, and does a different task depending on the matched value.

Syntax

In a switch/case block, you specify what you are checking against, then give a list of possible values you want to handle.


switch(value){// www . j  a v a 2 s .c  om
   case constant_1:
         do if the value is constant_1
         break;
   case constant_2:
         do if the value is constant_2
         break;
   case constant_3:
         do if the value is constant_3
         break;
   default:
         do if no one matched
         break;
}

Note

Each case construct has a break statement at the end of it. break exits the entire switch construct, ensuring that no more code blocks within the switch construct are run.

Example

The following code uses the switch statement to check string value.


<?php/*from   w  ww  .j  a va 2  s . c  o  m*/
        $Name = 'Bob';
        switch($Name) {
        case "Jack":
                print "Your name is Jack\n";
                break;
        case "Linda":
                print "Your name is Linda\n";
                break;
        case "Bob":
                print "Your name is Bob\n";
                break;
        default:
                print "I don't know your name!\n";
        }
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition