Another interesting RFC recently landed to PHP community. So far the easiest way of explaining comprehensions for me comes from Python world:
Comprehensions are constructs that allow sequences to be built from other sequences.
Here’re some examples from List comprehensions in Python:
def palindromes(strings):
return [s + s[::-1] for s in strings]
def starting_with(letter, names):
return [name for name in names if name[0].lower() == letter.lower()]
JavaScript, however, decided to remove its support from standard in favour of filter/arrow/map functions.
The array comprehensions syntax is non-standard and removed starting with Firefox 58. For future-facing usages, consider using
Array.prototype.map
,Array.prototype.filter
, arrow functions, and spread syntax.
Speaking of PHP RFC, that’s what we might get if RFC gets approved:
$gen = [for $list as $x if $x % 2 yield $x*2];
//equivalent to:
$gen = (function() use ($list) {
foreach ($list as $x) {
If ($x % 2) {
yield $x * 2;
}
}
})();
Personally, I would vote in favour of this. Maybe, it’s nostalgia about Perl one-liners and how elegant you can solve some basic stuff. I think PHP needs this syntactic sugar, giving people choice of using closure calls and comprehensions.