Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

This question already has an answer here:

Hi I have an array like below.

  $arr = Array ( [My_name] => Sam [My_location] => United_Kingdom [My_id] => 1 );

And im trying to change the keys from

  My_name, My_Location, My_id

to

  Your_name, Your_Location, Your_id

So the final array would look like

  Array ( [Your_name] => Sam [Your_location] => United_Kingdom [Your_id] => 1 );

I was hoping something like str_replace would work

   $arrnew = str_replace("My","Your",$arr);

But this is only replacing "My" to "Your" if "My" is a value, not a key.

So how would I change the keys?

Thanks for any help.

share|improve this question

marked as duplicate by John Conde, Eric, Leri, kumar_v, 2ndkauboy Mar 7 '14 at 13:10

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
The best option is probably to create your array with more generic keys such as name, id, and location in the first place – Mark Baker Jul 20 '13 at 16:32
up vote 5 down vote accepted
$arrnew = array_combine(str_replace("My","Your",array_keys($arr)), $arr);
share|improve this answer
    
+1 for remembering that str_replace will work on an array as well as on a string – Mark Baker Jul 20 '13 at 16:27

you cannot change the keys in-place but you can do something like this:

foreach($arr as $key => $value) {
    $arr[str_replace("My","Your",$key)] = $value;
    unset($arr[$key]);
}

This will add a new element with the new keys unsetting the old element

Hope this helps

share|improve this answer

You could try this:

foreach($arr as $key => $val){
    $newkey = str_replace("My","Your",$key);
    unset($arr[$key]);
    $arr[$newkey] = $val;
}

Demo: http://codepad.org/3vKkmAXx

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.