PHP SWITCH




PHP Tutorial > PHP Commands > SWITCH

SWITCH is used in PHP to replace nested IF..ELSE loops, and is similar to the CASE command in other computer languages. The basic syntax of SWITCH is as follows:

SWITCH ($variable) {
CASE 'value 1':
  [code to execute when $variable = 'value 1']
  break;
CASE 'value 2':
  [code to execute when $variable = 'value 2']
  break;
CASE 'value 3':
...
DEFAULT:
  [code to execute when none of the CASE values matches $variable]
}

There can be an unlimited number of CASE conditions. In addition, DEFAULT is optional.

Let's view an example. Assuming we have the following piece of code:

$sample = 10;
SWITCH ($sample) {
CASE 30:
  print "Value is 30";
  break;
CASE 25:
  print "Value is 25";
  break;
CASE 20:
  print "Value is 20";
  break;
DEFAULT:
  print "Value is outside the range";
}

The output of the above code is:

Value is outside the range

This is because none of the CASE conditions was matched, so the code following DEFAULT is executed.

Next: PHP WHILE Loop



Copyright © 2014   1keydata.com  All Rights Reserved.  Privacy Policy