Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement > possible to include multiple case matches in a single case?

I'd like to pass multiple values in a single switch case. I realize its not possible they way I'm trying to do it. Is there another way, short of placing each case on its on line?

switch(get_option('my_template'))
{
case 'test1', 'test2':
return 850;
break;

default:
return 950;
}
like image 871
Scott B Avatar asked Apr 08 '11 16:04

Scott B


People also ask

Can a switch statement hit multiple cases?

A switch statement includes multiple cases that include code blocks to execute. A break keyword is used to stop the execution of case block. A switch case can be combined to execute same code block for multiple cases.

How do you use multiple cases in a switch case?

use multiple constants per case, separated by commas, and also there are no more value breaks: To yield a value from a switch expression, the break with value statement is dropped in favor of a yield statement.

Can switch have multiple conditions?

You can use multiple conditions in the switch case same as using in JavaScript if statement. You can do that but the switch statement will switch on the result of the expression you provide. Given you have a logical and ( && ) in your expression there are two possible outcomes defined on how && works.

Can we have multiple statements in a single case block?

You can use multiple break statements inside a single case block in JavaScript and it will act just like multiple return statements inside of a single function.


2 Answers

switch(get_option('my_template')) {
    case 'test1':
    case 'test2':
        return 850;
        break;    
    default:
        return 950;
}
like image 117
racetrack Avatar answered Oct 01 '22 12:10

racetrack


Within the switch structure i dont believe there is any way of doing something like an 'or' on one line. this would be the simplest way:

switch(get_option('my_template')) 
{ 
   case 'test1':
   case 'test2': 
     return 850; break;  

   default:
     return 950; 
} 

But, especially if you are only returning a value and not executing code, i would reccomend doing the following:

$switchTable = array('test1' => 850, 'test2' => 850);
$get_opt = get_option('my_template');
if in_array($get_opt, $switchTable)
    return $switchTable[$get_opt];
else return 950;
like image 28
jon_darkstar Avatar answered Oct 01 '22 14:10

jon_darkstar