PHP » Control Structures » switch

Syntax:
switch ($var) {
   value1:
      // block 1
   value2:
      // block 2
   default:
      // default block
}

Chooses a block of code to execute based on a value.

When the choice of a block of code to run is based on the value of a single variable, the switch control structure is often a good alternative, especially when there are many possible values. switch can only be used with integers, floats, and strings. The code at the first matching case statement is executed. Unless the block of code inside the case statement is ended with "break;", all the following blocks will also be executed. When several values should result in the same block being executed the break statement should not be used.

Examples

Code:
<?php

$a = "PHP 3";

switch ($a) {
   case "PHP 4":
      print "New PHP version";
       break;
   case "PHP 5":
      print "Very new PHP version";
       break;
   default:
      print "Old PHP version";
}

?>
Output:
Old PHP version
Explanation:

A switch statement is used to print different messages depending on the contents of a string.

See Also: