note 125580 added to control-structures.match

From: Date: Wed, 09 Dec 2020 00:50:40 +0000
Subject: note 125580 added to control-structures.match
Groups: php.notes 
Request: Send a blank email to php-notes+get-215953@lists.php.net to get a copy of this message
As well as being similar to a switch, match expressions can be thought of as enhanced lookup tables — for when a simple array lookup isn't enough without extra handling of edge cases, but a full switch statement would be overweight. For a familiar example, the following <?php function days_in_month(string $month): int { static $lookup = [ 'jan' => 31, 'feb' => 0, 'mar' => 31, 'apr' => 30, 'may' => 31, 'jun' => 30, 'jul' => 31, 'aug' => 31, 'sep' => 30, 'oct' => 31, 'nov' => 30, 'dec' => 31 ]; $name = strtolower(substr($name, 0, 3)); if(isset($lookup[$name])) { if($name == 'feb') { return is_leap($year) ? 29 : 28; } else { return $lookup[$name]; } } throw new InvalidArgumentException("Bogus month"); } ?> with the fiddly stuff at the end, can be replaced by <?php function days_in_month(string $month): int { return match(strtolower(substr($name, 0, 3))) { 'jan' => 31, 'feb' => is_leap($year) ? 29 : 28, 'mar' => 31, 'apr' => 30, 'may' => 31, 'jun' => 30, 'jul' => 31, 'aug' => 31, 'sep' => 30, 'oct' => 31, 'nov' => 30, 'dec' => 31, default => throw new InvalidArgumentException("Bogus month"), }; } ?> Which also takes advantage of "throw" being handled as of PHP 8.0 as an expression instead of a statement. ---- Server IP: 45.112.84.4 Probable Submitter: 45.112.85.244 (proxied: 125.239.154.159) ---- Manual Page -- http://php.net/manual/en/control-structures.match.php Edit -- https://master.php.net/note/edit/125580 Del: integrated -- https://master.php.net/note/delete/125580/integrated Del: useless -- https://master.php.net/note/delete/125580/useless Del: bad code -- https://master.php.net/note/delete/125580/bad+code Del: spam -- https://master.php.net/note/delete/125580/spam Del: non-english -- https://master.php.net/note/delete/125580/non-english Del: in docs -- https://master.php.net/note/delete/125580/in+docs Del: other reasons-- https://master.php.net/note/delete/125580 Reject -- https://master.php.net/note/reject/125580 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#215953) next »