DEV Community

Cover image for PHP proposal: List Comprehension (like in Python)
Eric The Coder
Eric The Coder

Posted on

PHP proposal: List Comprehension (like in Python)

There is a proposition on the table for PHP to add List Comprehension in a future version release.

For those who dont know what is List Comprehension we can define it as a shorthand syntax that offers a more compact, readable, and expressive way to define common list interactions.

Many languages have comprehensions of some form or another, and the syntax varies widely between them. The specific syntax proposed for PHP was initially inspired by Python.

You can see detail explanation with more examples here: https://wiki.php.net/rfc/comprehensions

Here a example

// Normal interation
$gen = (function() use ($list) {
  foreach ($list as $x) {
    If ($x % 2) {
     yield $x * 2;
    }
  }
})();

// Shorthand List Comprehension
$gen = [for $list as $x if $x % 2 yield $x*2];

// General form
'[' ('for' <iterable expression> 'as' $key '=>' $value ('if' <condition>)?)+ (yield <expression>)? ']'
Enter fullscreen mode Exit fullscreen mode

So what do you think about that? For my part, I use List Comprehension in Python and I love it, so cant wait!

Top comments (0)