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!
PythonServer Side ProgrammingProgramming. We can create new sequences using a given python sequence. This is called comprehension. It basically a way of writing a concise code block to generate a sequence which can be a list, dictionary, set or a generator by using another sequence.
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.
If you're wondering if JavaScript supports a list comprehension syntax like Python, the answer is unfortunately no. The JavaScript Committee TC39 once considered adding list comprehension to JavaScript, but it was canceled in favor of other JavaScript array methods like filter() and map() .
Python is famous for allowing you to write code that's elegant, easy to write, and almost as easy to read as plain English. One of the language's most distinctive features is the list comprehension, which you can use to create powerful functionality within a single line of code.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With