Hi everybody!
Has this idea been discussed before?
I find myself writing switch statements in PHP quite rarely. This has a few
reasons:
1. It doesn’t have a "strict_types” version
2. It is quite verbose (lots of breaks)
3. It is a statement rather than an expression
Often, if / elseif statements turn out to be shorter, safer and easier to read
than the switch statement.
What I’d really love is something like a match expression:
```
$r = match ($x) {
1: ‘Tiny’;
<= 10: ‘Small’;
<= 20: ‘Medium’;
<= 30: ‘Large’;
range(31, 100): ‘Enormous’; // Equivalent to `in_array($x, range(31, 100),
true)`
instanceof Foo, instanceof Bar: ‘What?’;
default: ‘Unknown’;
};
```
These are the main differences compared to a traditional `switch` statement:
- The whole `match` is an expression, the result of the executed `case` is
implicitly returned
- It allows pattern matching, not just `==` comparison, `===` is the default
- It does no implicit type conversion, thus no unexpected results when mixing
strings and numbers
- Each case has an implicit `break`
- Where you’d previously use two `case`s without a break, you now combine
conditions using a comma
One downside, since PHP doesn’t implicitly return the last statement as some
languages do there’s no obvious way to do multi-statement cases.
I assume that some people will not be so happy about having to switch-like
constructs. IMO the implicit type conversion is the biggest issue here. Maybe
we could offer a solution for this one at least.
Just some random thoughts.
Regards