Reputation: 2458
Can I write a switch statement like this?
switch ($mood) {
case hungry :
case sad :
echo 'Eat a chocolate';
case sad :
echo 'Call Up your friend';
}
Is this a good practice?
EDIT : Removed the break statement, based on the comment.
Upvotes: 3
Views: 3082
Reputation: 398
This question shown on top for a search, so I wanted to write correct approach. You don't need to write case "sad" multiple times, if it enters to case "sad" it will continue down until "break".
$mood= "sad";
switch ($mood) {
case "sad" :
echo 'Eat a chocolate';
case "hungry" :
echo 'Call Up your friend';
}
or
$mood= "sad";
switch ($mood) {
case "sad" :
echo 'Eat a chocolate';
case "hungry" :
echo 'Call Up your friend';
break;
}
And I don't think it as bad practice because this is cleaner than if else statement.
A good use scenario is handling changes to database according to version of the code/plugin. For example if you have to make some changes according to version of the code on your update call, you can use this approach.
switch ($version)
{
case "1.0":
// add x field to table a
// remove y field from table a
case "1.1":
// add z field to table b
case "1.2":
// create a new table c
case "1.5":
// add field m to table c
}
So if version is 1.1, the code in 1.1 and below (until latest version) will be executed. So it is cleaner approach than if statements.
Upvotes: 0
Reputation: 76656
It is technically possible to define multiple cases with the same value, but only the first case will get executed. So it's pretty much useless.
From the switch()
documentation:
PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement.
Since the first case has a break
in it, further cases won't be executed and the code will exit the switch()
block.
Consider the following piece of code:
$var = 'sad';
switch ($var) {
case 'sad':
echo 'First';
break;
case 'sad':
echo 'Second';
break;
}
This will output First
.
If you want to execute multiple statements if a condition is TRUE
, then add them under the same case, like so:
switch ($var) {
case 'sad':
echo 'First';
echo 'Second';
break;
}
Upvotes: 5