Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding one character to each array key in PHP [duplicate]

Tags:

arrays

php

Possible Duplicate:
Fastest way to add prefix to array keys?

I had a quick question about arrays in PHP. I need to add a couple of characters to each key in an array, for instance:

name => Mark age => 23 weight = > 150

needs to be converted to:

r_name => Mark r_age => 23 r_weight => 150

Any help would be appreciated, thanks.

like image 825
jwBurnside Avatar asked Dec 03 '22 08:12

jwBurnside


1 Answers

Iterate the array, add a new item with the modified key and delete the original item:

foreach ($arr as $key => $val) {
    $arr['r_'.$key] = $val;
    unset($arr[$key]);
}

As foreach works with an internal copy of the array, you won’t run into an infinite loop.

like image 147
Gumbo Avatar answered Dec 21 '22 22:12

Gumbo