>>> 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?
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.
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.
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.
Because it's a very comprehensive way to describe a sequence (a set in math and other languages, and a list/sequence in Python).
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
)
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