rfc:short-match

PHP RFC: Short match

Introduction

The match() expression, introduced in PHP 8.0, matches one value against a series of others. For more complex cases, it's possible to provide a value of boolean true as the value to match against, allowing each branch to be arbitrarily complex as long as it results in a boolean. This RFC allows that case to be used as a default; It makes the value to match against optional, and defaults it to boolean true if not specified.

This functionality was included in the original Match expression v1 RFC. It was removed from the second Match expression v2 RFC for simplicity. However, the poll from the first RFC suggested this was a desired feature, so this RFC brings it back.

Proposal

This RFC would make only one change. In a match() expression, if the match subject were not provided, it would default to boolean true.

That is, this PHP 8.0 syntax:

$a = 3;
 
print match (true) {
  $a < 2 => 'small',
  $a == 3 => 'medium',
  default => 'large',
};

could, with this RFC, be shortened to:

$a = 3;
 
print match {
  $a < 2 => 'small',
  $a == 3 => 'medium',
  default => 'large',
};

A prime use case for such match statements is for basic pattern matching within a function:

function getNumberKind(int $num) {
  return match {
    $num > 0 => NumberKind::POSITIVE,
    $num == 0 => NumberKind::ZERO,
    $num < 0 => NumberKind::NEGATIVE,
  };
}

That would be even more compact if combined with the also-proposed Short Functions RFC. Or, if used with a short-lambda today:

$getNumber = fn(int $num) => match {
    $num < 0 => NumberKind::NEGATIVE,
    $num == 0 => NumberKind::ZERO,
    $num > 0 => NumberKind::POSITIVE,
};

The net result is to simplify both the writing and reading of “functions as expressions” rather than “functions as subroutines.”

Backward Incompatible Changes

None

Proposed PHP Version(s)

8.1

Proposed Voting Choices

Accept this RFC as proposed. 2/3 required for passage.

Patches and Tests

Implementation

References

rfc/short-match.txt · Last modified: 2022/04/17 19:06 by ilutov