PHP switch

In this chapter you will learn:

  1. When to use switch statement
  2. Syntax for PHP switch statement
  3. Note for switch statement
  4. Example - Using PHP switch statement

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){/*from   j a va 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// java 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.

Next chapter...

What you will learn in the next chapter:

  1. What is foreach loop
  2. foreach loop Syntax
  3. Example - Loop array with foreach loop
  4. Example - Iterating through a multidimensional array with foreach
  5. Example - Iterating Through Object Properties
Home » PHP Tutorial » PHP Statements
PHP Code Blocks
PHP Comments
PHP if
PHP if else
PHP switch
PHP foreach
PHP while loop
PHP do while loop
PHP for loop
PHP break
PHP continue
PHP Mixed-Mode Processing
PHP include/require