The switch> operator can include multiple matches in one case?

I would like to pass multiple values ​​in one case. I understand that this is not how I am trying to do it. Is there any other way without putting each case in its own line?

switch(get_option('my_template')) { case 'test1', 'test2': return 850; break; default: return 950; } 
+8
php switch-statement
source share
5 answers
 switch(get_option('my_template')) { case 'test1': case 'test2': return 850; break; default: return 950; } 
+24
source share

If you do not use break; in its case, execution simply falls into the following case. You can take advantage of this by adding each of your cases together, for example:

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

Since in the case of "test1" there is no break; when execution ends in this case (that is, immediately, since there is no logic in it), then the control will fall into the "test2" register, which will end in its break statement.

In this case, break is not even required for these cases, since the return will take care of exiting switch by itself.

+2
source share

In the switch structure, I do not believe that there is a way to do something like "or" on one line. this would be the easiest way:

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

But, especially if you are returning a value and not executing the code, I would recommend 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; 
+2
source share

I think this is as close as possible.

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

Edited with the fix.

+1
source share

How about this

 switch(get_option('my_template')) { case 'test1': case 'test2': return 850; break; default: return 950; } 
+1
source share

All Articles