There are more efficient ways of checking a variable than using a long list of PHP elseif statements. An alternative way of checking variables is using the switch statement.
The switch statement separates our code into blocks; each block representing the code to be executed if the condition which is being checked for is true.
By separating our code into blocks, the switch statement helps to make our code more readable; which is always useful.
Have a look below at our PHP switch tutorial.
The syntax for the switch statement in PHP is as follows:
switch ($variable) { case (something1): // do something break; case (something2): // do something break; case (something3): case (something4): // do something break; .... .... default: // do something break; }
The first thing to note is that the default case is not required and does not need to be used. What it does though is perform an action if none of the other conditions match.
Also, you can even have more than one conditions which do the same thing as shown with something3 and something4 above.
It is very important to put break statements after the block of code you want to execute for each case. This is because PHP will continue to execute the remaining code, thinking it is a part of the current block. Therefore we need to explicitly terminate a block and this is done with the break statement.
Below is an example of how the switch statement is used in PHP:
<?php $meal = 'Burger'; switch ($meal) { case 'Salad': echo 'One salad coming up'; break; case 'Pie': echo 'One pie coming up'; break; case ('Burger'): case ('Chicken Sandwich'): echo 'We currently have a special on this'; break; default: echo 'We don\'t have this on our menu'; break; } ?>
If we ran the above code, the result will be:
This is because the meal variable was set to 'Burger' and under the case for 'Burger' is the instruction to output 'We currently have a special on this'.
If we changed the $meal variable to 'Fries' we would get:
This is because we do not have a case that matches 'Fries', so our default case steps in and outputs 'We don't have this on our menu'. If we did not have a default case for our switch statement, when $meal was changed to 'Fries' we would not get any output from our script.
You can play around with code similar to what you saw above in this PHP switch tutorial to see how exactly the switch construct works.
The switch statement is more efficient than a block of elseif statements. This is because the interpreter makes one set of checks and matches the variable to a case and then goes directly to that case to execute it. This goes faster than the usual way of checking each condition one by one.
We hope this tutorial on the PHP Switch statement was enlightening.