Reputation: 2877
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!
Upvotes: 90
Views: 25968
Reputation: 756
Since PHP 7.4 you can also use arrow functions in array_map
:
<?php
$nums = range(0,9);
print_r(array_map(fn($x) => $x*$x,$nums));
// Array
// (
// [0] => 0
// [1] => 1
// [2] => 4
// [3] => 9
// [4] => 16
// [5] => 25
// [6] => 36
// [7] => 49
// [8] => 64
// [9] => 81
// )
Upvotes: 3
Reputation: 34293
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
Upvotes: -2
Reputation: 4318
PHP 5.5 may support list comprehensions - see the mailing list announcement:
And further discussion:
Upvotes: 5
Reputation: 301055
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));
Upvotes: 105