Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension (python)and array comprehension (php)?

>>> lst = ['dingo', 'wombat', 'wallaby']
>>> [w.title() for w in lst]
['Dingo', 'Wombat', 'Wallaby']
>>> 

In python there is simple ways to todo with list comprehension.

What about in php with array('dingo', 'wombat', 'wallaby'); ?

Are there array comprehension or any build in function ,or normally loop on it?

EDIT

function addCaps( Iterator $it )
{
    echo ucfirst( $it->current() ) . '<br />';
    return true;
}

/*** an array of aussies ***/
$array = array( 'dingo', 'wombat', 'wallaby' );

try
{
    $it = new ArrayIterator( $array );
    iterator_apply( $it, 'addCaps', array($it) );
}
catch(Exception $e)
{
    /*** echo the error message ***/
    echo $e->getMessage();
}

Look the code not too simple like I expected?

like image 943
kn3l Avatar asked Apr 14 '11 14:04

kn3l


People also ask

What is a list comprehension in Python?

A Python list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list. Python List comprehension provides a much more short syntax for creating a new list based on the values of an existing list.

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.

What is the difference between list and list comprehension?

Difference between list comprehension and for loop. The for loop is a common way to iterate through a list. List comprehension, on the other hand, is a more efficient way to iterate through a list because it requires fewer lines of code.

Why is it called list comprehension Python?

Because it's a very comprehensive way to describe a sequence (a set in math and other languages, and a list/sequence in Python).


Video Answer


1 Answers

You can use array_map() with anonymous functions (closures are PHP 5.3+ only).

$arr = array_map(function($el) { return $el[0]; }, array('dingo', 'wombat', 'wallaby'));
print_r($arr);

Output

Array
(
    [0] => d
    [1] => w
    [2] => w
)

Edit: OP's sample code

$arr = array_map('ucwords', array('dingo', 'wombat', 'wallaby'));
print_r($arr);

Output:

Array
(
    [0] => Dingo
    [1] => Wombat
    [2] => Wallaby
)
like image 98
Dogbert Avatar answered Oct 26 '22 22:10

Dogbert