Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do shorthand switch statements exist (in PHP)?

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:

  • I now have to write a new OR condition for each color
  • Every group of conditions adds an extra level of nesting

My 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.

like image 424
Bas Peeters Avatar asked Sep 30 '22 18:09

Bas Peeters


1 Answers

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
};
like image 152
Swooth Avatar answered Oct 03 '22 01:10

Swooth