4

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.

Community
  • 1
  • 1
jwBurnside
  • 849
  • 4
  • 31
  • 66

3 Answers3

15

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.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
1

Take a look at this post: In PHP, how do you change the key of an array element?

Community
  • 1
  • 1
roirodriguez
  • 1,685
  • 2
  • 17
  • 31
1

If you can be sure, that there are no two keys $K1,$K2 in your array with $K1 = "r_".$K2 , you can use the solution given by Gumbo - its efficient and nice.

If you can not guarantee the stated condition, i would prefer generating a new array with the altered keys and deleting/overwriting the old one afterwards. This is not as memory efficient as the other solution but wont fail.

Another thing to keep in mind is, that unset is a bit slow in PHP. So Unsetting a lot of elements in your array might be slower than working with a copy and deleting the original afterwards.

Sascha S.
  • 61
  • 2