0

I have a faint, faint memory that I have seen a solution for using ternary-like operators that works like a switch/case-statements in PHP. I may have seen it as an suggestion for future versions of PHP... I'm not sure, and I cannot find where I may have read it... or if my memory totally pranks me :)

The solution looked similar to this (the syntax is not correct though, I hope you understand anyway):

$weekday = $dayofweek ! 1 => "Monday", 2 => "Tuesday", ... , 7 => "Sunday" : "Unknown";

The alternative is to write...

switch ($dayofweek) { 
    case 1: $weekday = "Monday";  break;
    case 2: $weekday = "Tuesday"; break;
    ...
    case 7: $weekday = "Sunday";  break;
    default: $weekday = "Unknown";
}

(I am aware of that I can use arrays in this simple example.)

Does this operator based version of switch/case really exist? Or... have I remembered wrong? :)

Gowire
  • 1,046
  • 6
  • 27
  • 2
    Sounds like you're thinking of [match expression](https://kinsta.com/blog/php-8/#match-expression) that was introduced in PHP 8. – M. Eriksson Sep 09 '21 at 14:01
  • I think that it would be messy to have that type of syntax. (You can have chained conditions in one line, but again, it would be a mess). If the case is for weekdays, you can set an array of days or use the dedicated parameter of the "date()" function to retrieve day name. – Ofir Baruch Sep 09 '21 at 14:01
  • Ah... thanks @MagnusEriksson! I thought that I've seen it... That's what I looked for. I remembered it as an operator, but it was en expression syntax instead. – Gowire Sep 09 '21 at 14:02
  • 2
    Does this answer your question? [How to use match expression instead of switch expression](https://stackoverflow.com/questions/62983592/how-to-use-match-expression-instead-of-switch-expression) - Just so we can close it as a dupe that already has an explanation how it works. – M. Eriksson Sep 09 '21 at 14:06
  • `match` probably has advantages but similar to `$weekday = [1 => "Monday", 2 => "Tuesday", 7 => "Sunday"][$dayofweek] ?? "Unknown";` – AbraCadaver Sep 09 '21 at 14:09

0 Answers0