PHPmatch Expression
The PHP Match Expression
Thematch expression provides a new way to handle multiple conditional checks (like theswitch statement).
Thematch expression evaluates an expression against multiple alternatives (using strict comparison) and returns a value.
Tip:Thematch expression is new in PHP 8.0.
Here are the key differences betweenmatch andswitch:
- A
matchexpression has a more readable syntax thanswitch - A
matchexpression returns a value, whileswitchdoes not - A
matchexpression breaks automatically after a match, whileswitchrequiresbreak; - A
matchexpression has strict comparison (===), whileswitchuses loose comparison (==)
Syntax for match
$result = match($expression) { condition1 => returnvalue1, condition2 => returnvalue2, condition3, condition4 => returnvalue3, default => defaultvalue,}Tip: The default arm catches all expressions that are not matched.
The following example is equal to the example on theswitch page, but here we use the thematch expression:
Example
$favcolor = "red";$text = match($favcolor) { "red" => "Your favorite color is red!", "blue" => "Your favorite color is blue!", "green" => "Your favorite color is green!", default => "Your favorite color is neither red, blue, nor green!",};echo $text;Try it Yourself »Match Multiple Values
If you want thematch expression to match multiple values for the same code block, you can group them with commas, like this:
Example
Match multiple values:
$d = 3;$text = match($d) { 1, 2, 3, 4, 5 => "The week feels so long!", 6, 0 => "Weekends are best!", default => "Invalid day",};echo $text;Try it Yourself »The default Keyword
In amatch expression, theremust be a condition that matches the expression,or a default case, to handle it.
If there are no matches, and no default case, thematch expression throws an UnhandledMatchError exception.
Example
This will throw an UnhandledMatchError exception:
$favcolor = "pink"; // no conditions will match thistry { $text = match($favcolor) { "red" => "Your favorite color is red!", "blue" => "Your favorite color is blue!", "green" => "Your favorite color is green!", };} catch (\UnhandledMatchError $e) { var_dump($e);}echo $text;Try it Yourself »
