Skip to main content

PHP match Expression

PHP 8.0 added the match expression, a close relative of switch. There are three main differences: it produces a value, it compares with strict comparison (===), and it needs no break statements.

Basic match expression

The value of $status decides which string match gives back, and that string is stored in $text:

Prompt
Write a PHP script that sets a variable $status to 1. Use a match expression to assign a string to $text: 1 maps to "Ready", 2 maps to "Set", 3 maps to "Go". Print $text.
Output: PHP script

The default Keyword

A default arm catches everything the other arms don't. It is worth adding, because if no arm matches and there is no default, PHP throws an UnhandledMatchError.

Match with default

No arm covers the value 5, so the default arm supplies the result:

Prompt
Write a PHP script that sets a variable $status to 5. Use a match expression with a default arm. Cases 1, 2, 3 map to "Ready", "Set", "Go" respectively. The default maps to "Unknown". Print the result.
Output: PHP script

Multiple Values Per Arm

One arm can cover several values: write them separated by commas. That arm is chosen if the expression matches any one of them.

Match with multiple values

Here the days are grouped into three arms, with commas between the values in each:

Prompt
Write a PHP script that sets a variable $day to 2. Use a match expression where days 1 and 2 map to "Weekday start", days 3, 4 and 5 map to "Mid/late weekday", and days 6 and 7 map to "Weekend". Print the result.
Output: PHP script

Strict Comparison

Because match compares with ===, a value must have the right data type as well as the right content. A switch statement is more relaxed, since it compares loosely (==).

Match strict comparison

The string "1" fails to match the integer 1 under strict comparison, so the default arm is used:

Prompt
Write a PHP script that sets a variable $status to "1" (a string). Use a match expression where integer 1 maps to "Integer match". Add a default arm that maps to "No match". Print the result to show that match uses strict comparison.
Output: PHP script