Switch Statements
The switch statement in PHP is a type of control structure that allows you to execute different pieces of code based on the value of a single expression. The switch
statement compares the value of the expression to the values of multiple cases and executes the code associated with the first case that matches.
Basic syntax
Here's the basic syntax for a switch
statement in PHP:
switch (expression) {
case value1:
// code to be executed if expression = value1;
break;
case value2:
// code to be executed if expression = value2;
break;
case value3:
// code to be executed if expression = value3;
break;
default:
// code to be executed if the expression doesn't match any of the values
break;
}
The expression
in a switch
statement can be any expression that returns a value (integer, string, or float).
The case
statements define the different values to be tested against the expression
. Each case is followed by a colon (:
) and a block of code that will be executed if the expression matches that case.
The break
statement is used to break out of the switch
statement once a matching case has been found and its code has been executed. If a break
statement is not included at the end of a case, the code from that case will continue to execute until the end of the switch
statement or the next break
statement.
The default
case is used to provide a fallback option in case the expression does not match any of the case
values. If the default
case is not provided and no matching case is found, the switch
statement will simply exit without executing any code.
Using switch statements
Switch statements seem to be similar to if
statements.
Using an if statement
For example, let's say we wanted to display the day of the week to the user. We can do this with a chain of if elseif
statements like so:
This would output the following:
Today is Monday.
While this solution is viable, you may want to use a switch statement when trying to write cleaner code.
$day = "Monday";
if ($day === "Monday") {
echo "Today is Monday.";
} elseif ($day === "Tuesday") {
echo "Today is Tuesday.";
} elseif ($day === "Wednesday") {
echo "Today is Wednesday.";
} elseif ($day === "Thursday") {
echo "Today is Thursday.";
} elseif ($day === "Friday") {
echo "Today is Friday.";
} elseif ($day === "Saturday") {
echo "Today is Saturday.";
} elseif ($day === "Sunday") {
echo "Today is Sunday.";
} else {
echo "Unknown day.";
}
Switch statement example
Here's the same example but with a switch statement in PHP:
In this example, the switch
statement uses the variable $day
. The switch
statement then compares the value of $day
to the different case values and prints a message based on the matching case. If no matching case is found, the default
case is executed.
$day = "Monday";
switch ($day) {
case "Monday":
echo "Today is Monday.";
break;
case "Tuesday":
echo "Today is Tuesday.";
break;
case "Wednesday":
echo "Today is Wednesday.";
break;
case "Thursday":
echo "Today is Thursday.";
break;
case "Friday":
echo "Today is Friday.";
break;
case "Saturday":
echo "Today is Saturday.";
break;
case "Sunday":
echo "Today is Sunday.";
break;
default:
echo "Unknown day.";
break;
}
Alternative syntax
Alternatively, you can use the following syntax to produce a switch
statement. Instead of using curly brackets, you can use the endswitch
keyword to denote the end of the statement.
$day = "Monday";
switch ($day) :
case "Monday":
echo "Today is Monday.";
break;
case "Tuesday":
echo "Today is Tuesday.";
break;
case "Wednesday":
echo "Today is Wednesday.";
break;
case "Thursday":
echo "Today is Thursday.";
break;
case "Friday":
echo "Today is Friday.";
break;
case "Saturday":
echo "Today is Saturday.";
break;
case "Sunday":
echo "Today is Sunday.";
break;
default:
echo "Unknown day.";
break;
endswitch;
Fall-through behavior
In programming, "fall-through" behavior specifically relates to switch statements.
In a switch
statement, you can have multiple case
blocks, each representing a different condition. When the switch
statement is run, it checks each case
one by one until it finds one that matches. When a match is found, it starts executing the code inside that case.
Now, here's where "fall-through" comes in. If a case
doesn't end with a break
statement, the program doesn't stop at the end of that case
. Instead, it "falls through" to the next case
and starts executing the code there, even if the case
condition doesn't match. It'll keep doing this, executing code from subsequent case blocks until it hits a break statement or runs out of case blocks.
Here's an example to illustrate:
$fruit = "Apple";
switch ($fruit) {
case "Apple":
echo "You chose Apple. ";
case "Banana":
echo "You chose Banana. ";
case "Cherry":
echo "You chose Cherry. ";
break;
}
In this example, if $fruit
is "Apple"
, you might expect it to just echo "You chose Apple.". However, because of the fall-through behavior (lack of break statements after "Apple" and "Banana"), it will actually echo "You chose Apple. You chose Banana. You chose Cherry."
In general, you need to be careful with fall-through behavior. It can be useful in some scenarios where you want multiple case conditions to execute the same block of code, but it can also lead to unexpected results if you forget to include a break
statement.
Here's an example to illustrate this:
$fruit = "Apple";
switch ($fruit) {
case "Apple":
case "Banana":
case "Cherry":
echo "This is a common fruit.";
break;
case "Dragonfruit":
case "Kumquat":
echo "This is an exotic fruit.";
break;
default:
echo "I don't know this fruit.";
break;
}
In the example above, if $fruit
is "Apple"
, "Banana"
, or "Cherry"
, the code will echo "This is a common fruit.". This happens because when the switch
statement finds a matching case
, it executes all code until it hits a break
statement. In this case, since there's no break
after "Apple"
or "Banana"
, it will "fall through" to the next case until it finds a break.
Similarly, if $fruit
is "Dragonfruit"
or "Kumquat"
, the code will echo "This is an exotic fruit.".
If $fruit
is anything else, it will go to the default
case and echo "I don't know this fruit.". The default
case serves as a fallback if no other cases match.
The break
keyword is crucial in a switch
statement, because it tells PHP to exit the switch block and not execute any more code within it. If you omit the break
, PHP will continue to execute the next case or default block, even if it doesn't match the condition, which can lead to unexpected results.
if vs switch
The switch
and if
statements are both used to conditionally execute code in PHP, but there are a few key differences between the two:
- Syntax: The syntax for a
switch
statement is more compact than the equivalentif
statement. Aswitch
statement only requires a single expression to be evaluated, followed by a series ofcase
statements that determine what code to execute. Anif
statement, on the other hand, requires a complete if condition to be written for each possible outcome. - Speed:
switch
statements are generally faster thanif
statements when evaluating a large number of conditions. This is becauseswitch
statements are optimized for this type of evaluation, whereasif
statements require a series of condition evaluations. - Readability:
switch
statements can make code more readable, especially when there are a large number of conditions to evaluate. The case statements in aswitch
statement are clearly labeled, making it easy to see what code will be executed in each case. With anif
statement, it can become difficult to understand the code when there are many nestedif
conditions.
In general, you would use a switch
statement when you have a large number of conditions to evaluate, and the conditions are easily represented as a series of discrete outcomes. You would use an if
statement when you have a smaller number of conditions to evaluate, and the conditions are more complex and cannot be easily represented as discrete outcomes.
Exercises
Exercise #1
Create a simple program that outputs the name of the month based on the number. For example, if the number is 3, the month will be March.
Exercise #2
Rewrite the "switch" into an "if". Write the code using if..else
, which would correspond to the following switch
:
switch ($browser) {
case 'Edge':
echo "You've got the Edge!";
break;
case 'Chrome':
case 'Firefox':
case 'Safari':
case 'Opera':
echo 'Okay we support these browsers too';
break;
default:
echo 'We hope that this page looks ok!';
}
Exercise #3
Rewrite the code below using a single switch
statement:
$a = 1;
if ($a == 0) {
echo 0;
}
if ($a == 1) {
echo 1;
}
if ($a == 2 || $a == 3) {
echo '2,3';
}
Key takeaways
- The
switch
statement can be useful when comparing two values as opposed to using theif
statement. - Inside a
switch
statement, we can provide a list of values to compare with by using thecase
keyword. - If a match can't be found, a fallback can be provided with the
default
keyword. - Use the
break
keyword to prevent the rest of theswitch
statement from running.