4

I have an array like

$arr = array('key1' => 'hello');

Now I need to change key, is there any why I can achieve this

I know I can do this way:

$arr['key2'] = $arr['key1']; unset($arr['key1']);

But, is there any other way?

3
  • 1
    I think the copy / delete method is the best. Commented Dec 15, 2010 at 6:03
  • 1
    I don't think there is, but what's wrong with the method in your question? Commented Dec 15, 2010 at 6:03
  • @AgentConundrum: Nothing wrong in current method, but it will get worse when I need to edit lot's of keys Commented Dec 15, 2010 at 6:12

3 Answers 3

3

The way you've done it is the correct way. You cannot modify a key in an associative array. You can only add or remove keys. If you find yourself in need of doing many "key modifications" you may need to step back and evaluate whether you're using the most appropriate data structure for your problem.

Sign up to request clarification or add additional context in comments.

Comments

1

If you were a little crazy you could write a function.

function changeKey(array $array, $oldKey, $newKey) {

     if ( ! array_key_exists($array, $oldKey)) {
         return $array;
     }

     $array[$newKey] = $array[$oldKey];
     unset($array[$oldKey]);
     return $array;
}

This will do nothing if the original key isn't present. It will also overwrite existing keys.

4 Comments

thanks alex, and please check the link that is provided by Ben, it's nice
@IMJM I've been using PHP for years and have never ran into a problem where swapping keys was the solution.
me too using PHP for 7 years, but this time I am editing someone's code, which is badly written, so had no other choice, but still thanks for the help
@IMJM Ah yeah, I know all about that :)
0

Sounds like what this guy did

http://www.jbip.net/content/how-replace-keys-array-php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.