user1376704
user1376704

Reputation:

change the first letter of value of an array to uppercase

$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

Answers (4)

Joseph
Joseph

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

Austin Brunkhorst
Austin Brunkhorst

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

iWantSimpleLife
iWantSimpleLife

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

John Conde
John Conde

Reputation: 219804

Use array_map()

$new_array = array_map('ucfirst', $arr);

See it in action

Upvotes: 7

Related Questions