This content originally appeared on Envato Tuts+ Tutorials and was authored by Monty Shokeen
Have you ever wanted to compare the value of a variable or expression to multiple possible results and conditionally execute some code? There are many options available for you to do that. You could either use multiple if-else conditions or you could 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
vs if-else
: Direct Comparison
Lets begin with a simple example that shows direct comparison between using if-else
and switch-case
to control 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 multiple times to get different output. You will notice a few things.
Each case
statement is similar to an if
or elseif
block. The output you get from the if-else
section is same as the output from the switch-case
section. Always remember to use a break
statement to stop the execution of code for each case
statement.
Lets say you forgot to include break
with each case
block and the value of $animal
is 'Lion'. In that case, the code will output the location of lions, deer, and goats as well as the default statement about 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 that we use in the if-else
section. Remember that you cannot use multiple default
statements in your code.
Checking Multiple Conditions at Once
What do you do if there are multiple animals in the same section of the zoo? With if-else
blocks you can put them all inside one conditional statement using ||
to see if any of them evaluates to 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 Zebras are in the west section of the zoo. It skipped the code inside the first if block because that is only executed when the $animal
is an elephant, lion or goat.
Lets rewrite the above code in the form of switch-case
statements. You might 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 the east section of the zoo. So, what happened here?
The value or expression that we pass to switch
is loosely compared to the value or expression that we pass with each case
statement. Now, 'Elephant' || 'Lion || 'Goat'
ultimately evaluates to true
. This also returns true
when loosely compared to the value inside $animal
because a non-empty string is a truthy 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 multiple case
statements which are supposed to 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.'; }
We get the correct location of Zebras now and no visitor will get lost when looking for them.
Repeat Evaluation and Performance
One more thing that you should keep in mind is that the condition is evaluated only once when using switch
statement. On the other hand, it is evaluated multiple times when using if-else
statement, ie. once for each if
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; }
We make a call to the function most_populated()
which returns the name of a city. It simply returns New York in this case but it could easily be much more complicated and get city data from a web service for the passed country. Writing multiples if-else conditions in this case would have resulted in multiple calls to the most_populated()
function.
Obviously, we could avoid all those calls by storing the call result in a variable but using switch allows you to not use any variables at all.
Final Thoughts
In this tutorial, I showed you how to use switch-case
statements in PHP in place of if-else
blocks to execute code conditionally. We also saw how to write case
statements that cover multiple conditions. Finally, we learned how using switch-case
can be faster than if-else
blocks in certain situations.
This content originally appeared on Envato Tuts+ Tutorials and was authored by Monty Shokeen
Monty Shokeen | Sciencx (2022-07-16T04:53:40+00:00) PHP Case Statement Quick Reference. Retrieved from https://www.scien.cx/2022/07/16/php-case-statement-quick-reference/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.