开发者

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?


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
)


You don't have array comprehensions for PHP. You do have functions like array_walk() similar to the map() function of python.


array_map() and array_filter()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜