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

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

In python, there are easy todo methods with list comprehension.

And what about php with array('dingo', 'wombat', 'wallaby'); ?

Is there an understanding of the array or some kind of assembly function or, as a rule, a 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 at the code is not too simple, as I expected?

+4
source share
3 answers

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

 $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 code example

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

Output:

 Array ( [0] => Dingo [1] => Wombat [2] => Wallaby ) 
+8
source

You do not have arrays for PHP. You have functions like array_walk() , similar to map() functions for python.

+2
source

Source: https://habr.com/ru/post/1348105/


All Articles