Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 823
Darren Newton Avatar asked Aug 12 '09 15:08

Darren Newton


People also ask

What is comprehension equivalent in Python?

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.

What is list comprehension syntax in Python?

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.

Is there list comprehension in JavaScript?

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() .

Does Python have list comprehension?

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.


1 Answers

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)); 
like image 101
Paul Dixon Avatar answered Sep 22 '22 13:09

Paul Dixon