views:

417

answers:

2

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 would need to do some looping:

$output = array();
$Nums = range(0,9);

foreach ($Nums as $num) 
{
    $out[] = $num*=$num;
}
print_r($out);

to get:

Array ( [0] => 0 [1] => 1 [2] => 4 [3] => 9 [4] => 16 [5] => 25 [6] => 36 [7] => 49 [8] => 64 [9] => 81 )

Is there anyway to get a similar list comprehension syntax in PHP? Is there anyway to do it with any of the new features in PHP 5.3?

Thanks!

+10  A: 

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));
Paul Dixon
Nice answer. +1. Not exactly list comprehension, but it's a very elegant and short solution nevertheless. Have a care tho, this is PHP 5.3+ since an anonymous function is used.
Lior Cohen
PHP 5.3 required. But nice solution :)
Sebastian Hoitz
create_function() could probably be used with PHP < 5.3
Lior Cohen
you could use create_function, but it looks bloody ugly - far clearer just to define a new function IMHO!
Paul Dixon
Wow, very elegant! Another reason to upgrade to 5.3. Thanks!
Darren Newton
For comprehensions are a convenience over map, reduce and filter operations. For that matter between array_map, array_reduce, and array_filter you could have everything, a thin library using the __invoke() magic method and you could get a full on _pretty_ functional API.
Saem
+1  A: 

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

Rufinus