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?
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?
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.
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.