News:

GinGly.com - Used by 85,000 Members - SMS Backed up 7,35,000 - Contacts Stored  28,850 !!

Main Menu

PHP Switch

Started by VelMurugan, Apr 28, 2009, 06:41 PM

Previous topic - Next topic

VelMurugan

PHP 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:

QuoteSWITCH ($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.