PHP switch syntax

5 May 2009

In PHP there is a function called switch.

The switch syntax works like a lot of if and elseif statements, but is a lot less confusing and a lot more adaptable.

The function is started with switch (criteria)

Then you can define different cases that may be true.

If a case is true then it will carry out that portion of code and then carry on until the end of the switch syntax, or until it reaches the syntax saying "break;".

An example of a switch function is:

switch ($colour)
{
case "red":
echo "colour is red";
break;
case "blue":
echo "colour is blue";
break;
case "yellow":
echo "colour is yellow";
break;
}

If the $colour variable is actually set to "green" then none of the above will be true and so nothing will happen.

An alternative to nothing happening we can set a default for the switch function by using the syntax:

default:
echo "colour is not red, blue or yellow";
break;

If you want some of the cases to carry out the same piece of code you don't need to use the "break;" syntax.

Here's an example where you will not use the "break;" syntax in a switch function:

$weekday_num = 0;
switch ($day_now)
{
case "saturday":
$weekday_num = $weekday_num + 1;
case "friday":
$weekday_num = $weekday_num + 1;
case "thursday":
$weekday_num = $weekday_num + 1;
case "wednesday":
$weekday_num = $weekday_num + 1;
case "tuesday":
$weekday_num = $weekday_num + 1;
case "monday":
$weekday_num = $weekday_num + 1;
case "sunday":
$weekday_num = $weekday_num + 1;
break;
default:
echo "You have an error!";
break;
}
echo "It is day number " . $weekday_num . " so far this week.";

If in the above code the $day_now variable is set to tuesday then it will enter at tuesday and then will carry out all the code until it reaches the "break;" syntax. Then when we echo the result at the end it should read:

It is day number 3 so far this week.

Another example is finding how many days there are in a month using the switch syntax it will look like:

switch ($this_month)
{
case "january":
case "march":
case "may":
case "july":
case "august":
case "october":
case "december":
$num_days = "31";
break;
case "april":
case "june":
case "september":
case "november":
$num_days = "30";
break;
case "february":
$num_days = "28 or 29";
break;
}
echo "In this month there is " . $num_days . " days.";

If the $this_month variable is set to january then it will carry out all code until it reaches the "break;" switch syntax, and so it won't so anything until we set the $num_days variable to "31".

Also note, the only reason why we're using $num_days as a string variable is because on march we wanted to say "28 or 29".

The switch syntax is very similar to the Visual Basic select syntax.

http://www.peternichol.com/entry/trackback/103/

Please leave a comment using the form provided.