Make a Choice with SWITCH()

16Jan08

The switch() function lets you choose between several options, depending on the value some variable takes. It is similar, for those of you who have programmed in Visual Basic, to the select case command in that language.

So, let’s say you have a feedback form with a drop-down list of typical reasons someone might have for contacting your company. They have to categorize their message as

  1. request for information
  2. order not received
  3. order arrived damaged
  4. other

The form is programmed to assign the number next to each of those reasons to a variable $reason. Depending on the type of message, you want to route the form to different departments:

switch($reason)
{
case 1: $destination="fred@thiscompany.com"; break;
case 2: $destination="mary@thiscompany.com";break;
case 3: $destination="arnold@thiscompany.com";break;
default: $destination="bob@thiscompany.com";
}

Notice we didn’t assign #4 to the last option, but used ‘default’ a catch-all that is executed if none of the other values match. This way, bob will get any messages that do not have the $reason variable set. Also note that each option except the last needs a ‘break’ command at the end, to ensure that subsequent options are not considered. In this case, the default option would execute every time if you forgot the breaks.