I was hoping for something like this to work:
$bar = match (foo()) {
[] => throw Exception,
[, ] => throw Exception,
[$x] => $x,
};
Where, I'd test if foo()
gives array of exactly one element, and if it does, store that one element in $bar
, otherwise throw an exception.
Naturally, I can accomplish this with if
statements, but was hoping for something similar to this syntax to work.
It doesn't work both because it fails on [, ]
with Cannot use empty array elements in arrays
and on $x
with Undefined variable
- both of which is as expected.
My motivation is from functional programming where something similar would work. Is there a way to write something similar to my code above that would work?
The nearest I could think of would be to change the condition to use count()
so that if matches against the number of elements.
$bar = match (count($a = foo())) {
1 => current($a),
default => throw new Exception,
};
It's clumsy and would thing having to have the assignment in the check as well makes it less attractive.
As mentioned in the comments on the question,
No, pattern matching is not possible in PHP.
and
Specifically, I think this is the RFC which last got into pattern matching