Ever wanted to compare the value of a variable or expression with multiple possible results and conditionally execute some code? There are many options available to do this. You can use multiple if-else conditions or you can use switch-case statements.
In this tutorial, I will show you how to use switch-case in PHP to compare a variable with many different values.
Using switch-case
versus if-else
: Direct comparison
Let’s start with a simple example that shows the direct comparison between usage if-else
And switch-case
to control the program flow.
<?php $animals = ['Elephant', 'Lion', 'Deer', 'Goat', 'Crocodile', 'Zebra', 'Horse']; shuffle($animals); $animal = $animals[0]; // Outputs: Lions are in the south-west section of the zoo. if($animal == 'Elephant') { echo 'Elephants are in the south section of the zoo.'; } elseif($animal == 'Lion') { echo 'Lions are in the south-west section of the zoo.'; } elseif($animal == 'Deer') { echo 'Deer are in the north section of the zoo.'; } elseif($animal == 'Goat') { echo 'Goats are in the east section of the zoo.'; } else { echo 'Ask a tour guide.'; } // Outputs: Lions are in the south-west section of the zoo. switch($animal) { case 'Elephant': echo 'Elephants are in the south section of the zoo.'; break; case 'Lion': echo 'Lions are in the south-west section of the zoo.'; break; case 'Deer': echo 'Deer are in the north section of the zoo.'; break; case 'Goat': echo 'Goats are in the east section of the zoo.'; break; default: echo 'Ask a tour guide.'; } ?>
Try running the above code several times to get different output. You will notice a few things.
Each case
statement is similar to a if
or elseif
to block. The output you get from if-else
the section is the same as the output of switch-case
section. Always remember to use a break
statement to stop code execution for each case
declaration.
Let’s say you forgot to include break
with each case
block and the value of $animal
is ‘Leo’. If so, the code will display the location of lions, deer and goats, as well as the default declaration on the tour guide.
The default
statement is like a catch-all that handles all other values of $animal
. It is similar to the else
block we use in the if-else
section. Remember that you can’t use any more default
statements in your code.
Control of multiple conditions at the same time
What to do if there are multiple animals in the same section of the zoo? With if-else
blocks you can put them all inside a conditional statement using ||
to see if any of them evaluate true
. Here is an example:
$animal="Zebra"; // Outputs: Zebras are in the west section of the zoo. if($animal == 'Elephant' || $animal == 'Lion' || $animal == 'Goat') { echo $animal.'s are in the south section of the zoo.'; } elseif($animal == 'Zebra') { echo 'Zebras are in the west section of the zoo.'; } elseif($animal == 'Deer') { echo 'Deer are in the east section of the zoo.'; } else { echo 'Ask a tour guide.'; }
The code above would correctly tell us that the zebras are in the west section of the zoo. Skipped the code inside the first if block because it only runs when the $animal
it is an elephant, a lion or a goat.
We rewrite the above code in the form of switch-case
statements. You may be tempted to write it as shown below:
// Outputs: Zebras are in the east section of the zoo. switch($animal) { case 'Elephant' || 'Lion' || 'Goat': echo $animal.'s are in the east section of the zoo.'; break; case 'Zebra': echo 'Zebras are in the west section of the zoo.'; break; case 'Deer': echo 'Deer are in the north section of the zoo.'; break; default: echo 'Ask a tour guide.'; }
Look closely and you will see that the statement now says zebras are in East section of the zoo. So what happened here?
The value or expression to which we pass switch
is freely with respect to the value or expression we pass with each case
declaration. Now, 'Elephant' || 'Lion || 'Goat'
eventually evaluates true
. This also returns true
when vaguely compared with the value inside $animal
because a non-empty string is a true value. The code for the first case statement is then executed and we get the wrong location for the same zoo.
The correct way to handle more case
instructions which should execute the same section of code is by writing the case values on separate lines as shown below:
// Outputs: Zebras are in the west section of the zoo. switch($animal) { case 'Elephant': case 'Lion': case 'Goat': echo $animal.'s are in the east section of the zoo.'; break; case 'Zebra': echo 'Zebras are in the west section of the zoo.'; break; case 'Deer': echo 'Deer are in the north section of the zoo.'; break; default: echo 'Ask a tour guide.'; }
Now we get the correct position of the zebras and no visitors will get lost during the search.
Repeat the evaluation and performance
Another thing to keep in mind is that the condition is evaluated only once during use switch
declaration. On the other hand, it is evaluated several times during use if-else
statement, eg. once for each if
to block. Here is an example:
function most_populated($country) { return 'New York'; } // Outputs: This is not surprising at all. switch(most_populated('United States')) { case 'New York': echo 'This is not surprising at all.'; break; case 'Oakland': echo 'This does not seem correct.'; break; }
Let’s make a function call most_populated()
which returns the name of a city. In this case it simply returns New York, but it could easily be much more complicated and get the city data from a web service for the past country. Writing multiple if-else conditions in this case would have resulted in multiple calls to the most_populated()
function.
Of course, we could avoid all those calls by storing the call result in a variable, but using switches allows you to not use any variables.
Final thoughts
In this tutorial I have shown you how to use switch-case
PHP instructions instead of if-else
blocks to execute code conditionally. We also saw how to write case
statements that cover multiple conditions. Finally, we learned how to use switch-case
it can be faster than if-else
blocks in certain situations.