Introduced in PHP 8, the match
expression can be used to check a subject against multiple expressions. If a match is found, then its corresponding value is returned. The resulting value can either be stored in a variable or returned. For example:
// PHP 8+ $subject = 'expr2'; $result = match ($subject) { 'expr1' => 'foo', 'expr2', 'expr3' => 'bar', default => 'baz', }; echo $result; // 'bar'
As you can see from the example above, the expression arms may contain multiple expressions (separated by a comma). Also, please note that only single-line expressions are supported.
match
expressions must be terminated by a semi-colon (;
).
match
conditions (which can be any arbitrary expression) are checked top-down, in the following way:
- If a condition matches, then the corresponding value is returned and the remaining conditions are not evaluated;
- If a match is not found, then:
- If a
default
exists, the value associated with thedefault
pattern is returned; - Otherwise, an
UnhandledMatchError
is thrown.
- If a
For example:
// PHP 8+ $subject = 'no-match'; $result = match ($subject) { 'expr1' => 'foo', 'expr2' => 'bar', }; // Fatal error: Uncaught UnhandledMatchError
match
conditions are evaluated using strict comparison / identity check of a value (i.e. ===
). For example:
// PHP 8+ echo match (8.0) { '8.0' => 'not expected', 8.0 => 'expected', }; // 'expected'
However, you can also handle non-identity conditional cases in match
expressions by using true
as the subject expression, for example, like so:
// PHP 8+ $version = '7.0.1'; echo match (true) { $version >= '7' => 'supported', default => 'not supported', }; // 'supported'
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.