PHP SWITCH


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

Link to this page: If you find this page useful, we encourage you to link to this page. Simply copy and paste the code below to your website, blog, or profile.






Copyright 2007-2009  1keydata.com  All Rights Reserved.  Privacy Policy  



PHP Tutorial
PHP Variables
PHP Operators
PHP IF ELSE
PHP ELSEIF
PHP Switch
PHP While Loop
PHP FOR Loop
PHP DO WHILE Loop
PHP FOREACH Loop
PHP INCLUDE
PHP Functions
PHP ARRAY
PHP FORMS
PHP Cookies
PHP Redirect
PHP MySQL

PHP Commands

Resources