PHP » Control Structures » switch

switch ($var) {
      // block 1
      // block 2
      // 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.



$a = "PHP 3";

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

Old PHP version

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

See Also: