I'm trying to apply ucfirst
to the words in an array using array_walk
and an anonymous function. I want to change the values of the "original" array $fruits
. Since I can't use pass by reference, what can you recommend me to achieve that?
<?php
$fruits = array('apple', 'orange', 'banana', 'cherry');
array_walk($fruits, function($a) {
$fruits = ucfirst($a);
});
var_dump($fruits);
//results
array(4) {
[0] =>
string(5) "apple"
[1] =>
string(6) "orange"
[2] =>
string(6) "banana"
[3] =>
string(6) "cherry"
}
在这种情况下, array_map
是更好的功能。
$fruits = array_map('ucfirst', $fruits);
array_walk(
$fruits,
function(&$a) {
$a = ucfirst($a);
}
);
You could use the foreach loop:
$fruits = array('apple', 'orange', 'banana', 'cherry');
foreach($fruits as $key => $value)
{
$fruits[$key] = ucfirst($value);
}
$allUpperCase = array_map(function($fruit){
return ucfirst($fruit);
}, $fruits);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.