====== PHP RFC: Short match ====== * Version: 1.0 * Date: 2020-12-13 * Author: Larry Garfield (larry@garfieldtech.com) * Status: Inactive * First Published at: http://wiki.php.net/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 [[rfc:match_expression|Match expression v1]] RFC. It was removed from the second [[rfc:match_expression_v2|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 [[rfc:short-functions|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 ===== [[https://github.com/php/php-src/pull/6511|PR available here]] ===== Implementation ===== ===== References ===== * [[rfc:match_expression|PHP RFC: Match expression]] * [[rfc:match_expression_v2|PHP RFC: Match expression v2]] * [[rfc:short-functions|PHP RFC: Short Functions]]