Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use the same case value multiple times in a switch

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.

like image 470
Gokul N K Avatar asked Nov 19 '25 05:11

Gokul N K


1 Answers

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;
}
like image 169
Amal Murali Avatar answered Nov 21 '25 19:11

Amal Murali