is it posible for a PHP switch statement to take 2 arguements? For example:
switch (firstVal, secondVal){
case firstVal == "YN" && secondVal == "NN":
thisDesc = "this is the outcome: YN and NN";
break;
case firstVal == "YY" && secondVal == "NN":
thisDesc = "this is the outcome: YY and NN";
break;
}
Many thanks, I haven't done PHP in years!
No, you can't. A switch
-statement like
switch ($a) {
case 1:
break;
case 2:
break;
}
which is effectively the same as
if ($a == 1) {
} else if ($a == 2) {
}
You can use a slightly different construction
switch (true) {
case $firstVal == "YN" && $secondVal == "NN":
break;
case $firstVal == "YY" && $secondVal == "NN":
break;
}
which is equivalent to
if (true == ($firstVal == "YN" && $secondVal == "NN")) {
} else if (true == ($firstVal == "YY" && $secondVal == "NN")) {
}
In some cases its much more readable instead of infinite if-elseif-else
-chains.
No, but if your case is as simple as what you have, just concatenate the two inputs and test for the concatenated values:
switch ($firstval . $secondval) {
case "YNNN": ...
case "YYNN": ...
}
Old question, but i think this answer is not covered here:
You can pass multiple arguments to an array and pass that as the argument to the switch:
switch([$fooBah, $bool]) {
case ['foo', true]:
...
break;
case ['foo', false]:
case ['bah', true]:
...
break;
case ['bah', false]:
...
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