Skip to content

match

match (value) { ... } compares the value with each arm, in order. It returns the result of the first arm that is equal. match is an expression, so you can assign it or pass it to a function.

match

match chooses one value out of several by comparing a subject with a list of values.

You write the subject in brackets, then one arm per line. Each arm has one or more values on the left and a result on the right. The first arm with a value equal to the subject gives the result of the whole match. default is used when none of the other arms matched. It is tried last, wherever you put it in the list. A match is an expression, so you can assign it to a variable, pass it to a function or join it to a string.

Good to know: if no arm matches and there is no default, match throws a LogicError. The comparison is ==. An arm value of a type the subject can never be equal to does not compile. Text against a number is one example.

The examples below take these in turn: choosing a label for a value, choosing by a range with match (true), and writing the line a customer reads for each order status. The last two show a match inside an echo and a string, and an arm value that does not compile.

Choosing a label for a value

<?nvs
// Shows how `match` turns one value into another. Each arm has one or more
// values on the left and the result on the right. The first arm whose value
// equals the subject gives the result of the whole `match`.
class Day
{
public static function name(int $day): string
{
return match ($day) {
1, 2, 3, 4, 5 => 'weekday',
6 => 'Saturday',
7 => 'Sunday',
// `default` is used when none of the other arms matched.
default => 'not a day',
};
}
}
// This prints: day 3: weekday
echo 'day 3: ', Day::name(3), "\n";
// This prints: day 6: Saturday
echo 'day 6: ', Day::name(6), "\n";
// This prints: day 99: not a day
echo 'day 99: ', Day::name(99), "\n";
Output
day 3: weekday
day 6: Saturday
day 99: not a day

Choosing by a range instead of one value

<?nvs
// Shows the `match (true)` form. Here the left of each arm is a condition
// instead of a value, and the first condition that is true gives the result.
// Use it to choose by a range.
class Size
{
public static function unit(uint $bytes): string
{
// The arms are tested in order, so the largest range is written first.
return match (true) {
$bytes >= 1048576 => 'megabytes',
$bytes >= 1024 => 'kilobytes',
default => 'bytes',
};
}
}
// This prints: 512 bytes
echo '512 ', Size::unit(512), "\n";
// This prints: 4096 kilobytes
echo '4096 ', Size::unit(4096), "\n";
// This prints: 3145728 megabytes
echo '3145728 ', Size::unit(3145728), "\n";
Output
512 bytes
4096 kilobytes
3145728 megabytes

Writing the line a customer reads

<?nvs
// Shows what `match` is for at work: turning a stored status into the line a
// customer reads. A `match` is an expression, so it goes straight into the
// string being built. This one has no `default`, so a status nobody wrote an
// arm for throws a `LogicError` instead of sending a wrong message.
class Order
{
public function constructor(
public string $reference,
public string $status,
)
{}
}
class Mail
{
public static function line(Order $order): string
{
return 'Order ' . $order->reference . ': ' . match ($order->status) {
'paid', 'packing' => 'we are preparing your parcel',
'shipped' => 'your parcel is on its way',
'delivered' => 'your parcel has arrived',
};
}
}
array<Order> $orders = [
new Order('A-1', 'paid'),
new Order('A-2', 'shipped'),
new Order('A-3', 'cancelled'),
];
foreach ($orders as Order $order) {
try {
echo Mail::line($order), "\n";
} catch (LogicError $e) {
// "cancelled" has no arm, so this order is reported and the run
// carries on. This prints: Order A-3 has no message for cancelled
echo 'Order ', $order->reference, ' has no message for ', $order->status, "\n";
}
}
Output
Order A-1: we are preparing your parcel
Order A-2: your parcel is on its way
Order A-3 has no message for cancelled

A match inside a line and the error for no match

<?nvs
// Shows a `match` inside an `echo` and inside a string, and the error when no arm matches.
int $n = 2;
string $size = match ($n) {
1, 2 => 'low',
3 => 'three',
default => 'other',
};
// This prints: low mid
echo $size, ' ', match (true) { $n > 5 => 'big', $n > 1 => 'mid', default => 'small' }, "\n";
// This prints: n is two
echo 'n is ' . match ($n) { 2 => 'two', default => 'many' } . "\n";
// No arm matches 2 and there is no `default`, so `match` throws a `LogicError`.
try {
echo match ($n) { 1 => 'one' }, "\n";
} catch (LogicError $e) {
// This prints: no `match` arm matched the subject
echo $e->message, "\n";
}
Output
low mid
n is two
no `match` arm matched the subject

An arm that can never match

<?nvs
// Shows that an arm value of the wrong type does not compile. A string is never equal to an `int`.
// proof: compile-error
int $n = 1;
echo match ($n) {
'1' => 'one',
default => 'other',
}, "\n";
Output
error[E0466]: `int` and `string` are disjoint; no value is both, so this comparison is always false
--> 05-an-arm-that-can-never-match.nvs:7:5
|
7 | '1' => 'one',
| ^^^ compared here
= help: convert one side deliberately and then compare — `$s == ($n as string)`
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

The subject goes in brackets after match. Without the brackets, the code does not compile. The subject runs once, before any arm.

The arms are tested in the order they are written. An arm's values run one by one, and the test stops at the first match. The arms after it do not run. When two arms have the same value, the first one gives the result.

An arm may have several values, separated by commas. This works in match (true) too: $n > 5, $n < 0 => "far" matches when one of the two conditions is true. A comma after the last arm is allowed.

Each value is compared with the subject by ==. A mixed subject that contains the string "5" does not match the arm 5. A value whose type can never be equal to the subject is the error E0466. A string against an int is one such case. null against an int subject is another: the subject must be a ?int for that arm. In match (true), each condition must be a bool, and an int condition is E0466 too.

In match (true), a condition such as $m is int narrows the variable in that arm's result. match (true) { $m is int => $m + 1, default => 0 } gives 6 when $m is 5.

The type of a match is the union of its results. With the results "a" and 2, the type is string|int. Assigning that to a string variable is the error E0401.

A result is one expression. A block of statements in braces does not compile. A result may be a throw, such as default => throw new RuntimeError("bad").

A match with no arms is the error E0476. When no arm matches and there is no default, the LogicError has the message `no match arm matched the subject`. This also happens for an enum case that has no arm, because the compiler does not check that the arms list every case.

Use this when you test conditions in order

Section titled “Use this when you test conditions in order”

match (true) checks each arm’s condition, in order. It returns the result of the first condition that is true. This replaces a long chain of elseif.

match also works on enum cases. See Enums.

  • Do use match when each branch only gives a value.
  • Do write a default arm unless the arms list every possible value.
  • Don’t use match to run several statements in each branch. Use if or switch.
  • Don’t catch the LogicError of a missing arm to handle normal values. Add the arm or default.