Changing a PHP Array Key

I have an array like

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

Now I need to change the key, is there any reason to achieve this

I know I can do this:

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

But is there any other way?

+4
source share
3 answers

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 source key is missing. It will also overwrite existing keys.

+1
source

How you did it is the right way. You cannot change the key in an associative array. You can add or remove keys. If you need to make a lot of โ€œkey changes,โ€ you may need to step back and evaluate whether you are using the most appropriate data structure for your problem.

+3
source
0
source

Source: https://habr.com/ru/post/1332186/


All Articles