4 ms·
The Match Expression feature is interesting. According to the PHP docs, it can even handle non-identity expression, although the approach seems a little hacky:
by Minor49er 4y ago
The Match Expression feature is interesting. According to the PHP docs, it can even handle non-identity expression, although the approach seems a little hacky:
https://www.php.net/manual/en/control-structures.match.php#example-137 https://www.php.net/manual/en/control-structures.match.php#e...
<?php
$age = 23;
$result = match (true) {
$age >= 65 => 'senior',
$age >= 25 => 'adult',
$age >= 18 => 'young adult',
default => 'kid',
};
The above example will output:
string(11) "young adult"
- ryangittins 4y agoI've seen the same hack done with `switch (true)` in pre-PHP8 code (and other languages) as well.
- gremlinsinc 4y agomatch is basically a cleaner, more succinct switch, I hardly ever used switches before, though I use match a LOT. switch ($i) { case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; } verses: $output = match($i) { 0 => 'i equals 0', 1 => 'i equals 1', 2 => 'i equals 2', default => 'i is unknown' } echo $output; the result is basically the same, but match is more of an enclosed switch that just returns instead of does side effects, then you can do what you like w/ that. Ymmv, but match is a great code saver, and is very nice for enums and methods on enums. Before match i'd probably do something like: $output = 'i is unknown'; if($i == 0){ return 'i equals 0'; } if($i == 1) { return 'i equals 1'; } if ($i == 2) { return 'i equals 2'; } return $output; Not really, I'd probably do.. if($i) { return "i equals {$i}"; } return 'i is unknown'; but the point was if I had to check for multiples to match something, then do something else, that's how I would do it... albeit this is a simple case with a better solution.
- jw1224 4y agoI use `match` like this a lot now, often with PHP 8.1's enums[1]. It makes it easy to write clean dynamic accessors, without all the extra blocks required with multiple `if` branches: /** Check the status of this Task instance. */ public function status(): Status { return match (true) { $this->inProgress() || $this->isInReview() => Status::Started, $this->isApproved() || $this->isRejected() => Status::Finished, default => Status::Planned, }; } [1] https://stitcher.io/blog/php-enums https://stitcher.io/blog/php-enums
- randomguy0 4y agoWhat am I missing? Isn’t that the output that makes sense? Or am I misunderstanding your comment about it being hacky?
- generallee5686 4y agoI think they're talking about the "match (true)".
- Minor49er 4y agoYou are correct. This is what I was referring to