I have the following code:
<?php
echo check('three');
function check($string) {
switch($string) {
case 'one' || 'two' : return 'one or two'; break;
case 'three' || 'four' : return 'three or four'; break;
}
}
Currently it outputs:
one or two
But obviously I want the code to return three or four
.
So what is right method to return the same code for multiple case statements?
Not possible. the case
items must be VALUES. You have expressions, which means the expressions are evaluated, and the result of that expression is them compared against the value in the switch()
. That means you've effectively got
switch(...) {
case TRUE: ...
case TRUE: ...
}
You cannot use multiple values in a case. YOu can, however, use the "fallthrough support":
switch(...) {
case 'one':
case 'two':
return 'one or two';
case 'three':
case 'four':
return 'three or four';
}
Just write two case statements which execute the same code, e.g.
function check($string) {
switch($string) {
case 'one':
case 'two':
return 'one or two';
break;
case 'three':
case 'four' :
return 'three or four';
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With