Reputation:
$arr = array ('name'=>'bunt','game'=>'battlefield','fame'=>'hero');
foreach ($arr as $key=>$val){
$val = ucfirst($val);
}
var_dump($arr);
// result would be
// 'name' => 'Bunt', 'game' => 'Battlefield', 'fame' => 'Hero'
I am missing something here.... How to accomplish this ?
Upvotes: 1
Views: 4549
Reputation: 5160
Why not just use the key to access the array?
<?php
$arr = array('name' => 'bunt', 'game' => 'battlefield');
foreach ($arr as $key => $val) {
$arr[$key] = ucfirst($val);
}
var_dump($arr);
Upvotes: 0
Reputation: 21130
$val
is just a temporary variable in each iteration. To update the value of each key you need to pass it as a reference. Do this.
foreach ($arr as $key => &$val) {
$val = ucfirst($val);
}
Notice the &
following $val
.
Here's some documentation on references in PHP.
Upvotes: 2
Reputation: 1954
foreach ($arr as $key=>&$val){ $val = ucfirst($val); }
Put an & sign before $val . that will make it reference the variable instead of assigning the value.
Upvotes: 0