Does PHP have an equivalent to Python's list comprehension syntax?

前端 未结 4 1848
轻奢々
轻奢々 2020-12-08 09:17

Python has syntactically sweet list comprehensions:

S = [x**2 for x in range(10)]
print S;
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In PHP I wo

相关标签:
4条回答
  • 2020-12-08 09:52

    not out of the box, but take a look at: http://code.google.com/p/php-lc/ or http://code.google.com/p/phparrayplus/

    0 讨论(0)
  • 2020-12-08 09:56

    PHP 5.5 may support list comprehensions - see the mailing list announcement:

    • [PHP-DEV] List comprehensions and generator expressions for PHP (28 Jun 2012)

    And further discussion:

    • What Generators Can Do For You (by ircmaxell; 23 Jul 2012) - has a Fibonacci example.
    • What PHP 5.5 might look like (by NikiC; 10 Jul 2012)
    • Request for Comments: Generators (Wiki started 05 Jun 2012)
    0 讨论(0)
  • 2020-12-08 10:00

    In .NET, the equivalent of Python's "syntactically sweet list comprehensions" is LINQ. And in PHP, there're several ports of it, including YaLinqo library*. Syntactically, it's closer to SQL rather than a sequence of traditional constructs with for and if, but functionally, it's similar:

    $a = Enumerable::range(0, 10)->select('$v * $v');
    

    This produces an iterator which can either be output to console:

    var_dump($a->toArray()); // by transforming the iterator to an array
    echo $a->toString(', '); // or by imploding into a string
    

    or iterated over using foreach:

    foreach ($a as $i)
        echo $i, PHP_EOL;
    

    Here, '$v * $v' is a shortcut for function ($v) { return $v * $v; } which this library supports. Unfortunately, PHP doesn't support short syntax for closures, but such "string lambdas" can be used to make the code shorter.

    There're many more methods, starting with where (if equivalent) and ending with groupJoin which performs joining transformation with grouping.

    * developed by me

    0 讨论(0)
  • 2020-12-08 10:03

    Maybe something like this?

    $out=array_map(function($x) {return $x*$x;}, range(0, 9))
    

    This will work in PHP 5.3+, in an older version you'd have to define the callback for array_map separately

    function sq($x) {return $x*$x;}
    $out=array_map('sq', range(0, 9));
    
    0 讨论(0)
提交回复
热议问题