I want to compare the same variable (or expression) with many different values, and return a different value depending on which value it equals to. I want to do this inline or shorthand, as is possible with an if
statement.
Take the following switch
statement:
switch($color_name) {
case 'red':
case 'blue':
$color_type = handlePrimaryColor($in);
break;
case 'yellow':
case 'cyan':
$color_type = handleSecondaryColor($in);
break;
case 'azure':
case 'violet':
$color_type = handleTertiaryColor($in);
break;
default:
$color_type = null;
break;
}
I don't like writing $color_type =
in every case and would like to find a way to do this with less code.
I could do it with some form of shorthand syntax. Below, I use a shorthand if
statement to assign a value to the variable in the same place where it is first being declared:
$color_type = $color_name == 'red' || $color_name == 'blue'
? handlePrimaryColor($color_name)
: ($color_name == 'yellow' || $color_name == 'cyan'
? handleSecondaryColor($color_name)
: ($color_name == 'azure' || $color_name == 'violet'
? handleTertiaryColor($color_name)
: null
)
);
This method doesn't require declaring the variable within each construct, but gives me 2 new problems instead:
OR
condition for each colorMy question: Is there a method which allows me to directly assign a value to a variable using shorthand syntax that behaves like a switch?
If there isn't, I would be interested in learning why that limitation exists.
Since PHP 8.0 there is a shorthand switch available which is called match
$colorType = match($color) {
'red', 'blue' => handlePrimaryColor($in),
'yellow', 'cyan' => handleSecondaryColor($in),
'azure', 'violet' => handleTertiaryColor($in),
default => null
};
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