Change the key of an array element in PHP
This article demonstrates how to change the key of an array element in PHP.
1. Using unset() function
A simple solution is to insert a new element in the array with a key equal to the new key and a value equal to the value associated with the original key. Then, use the unset() function to remove the original key from the array.
Note that, this works, but destroys the ordering of the array. However, if the key is present at the end of the array, the order of the array remains unchanged.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php $arr = array('one' => 'a', 2 => 'b', 'three' => 'c'); $old_key = '2'; $new_key = 'two'; $arr[$new_key] = $arr[$old_key]; unset($arr[$old_key]); print_r($arr); /* Output: Array ( [one] => a [three] => c [two] => b ) */ ?> |
It is recommended to check if the key is present in the array before accessing it, otherwise, you get the PHP Warning: Undefined array key notice. This can be done using the array_key_exists() function, which returns true if the given key is set in the array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php $arr = array('one' => 'a', 2 => 'b', 'three' => 'c'); $old_key = '2'; $new_key = 'two'; if (array_key_exists($old_key, $arr)) { $arr[$new_key] = $arr[$old_key]; unset($arr[$old_key]); } print_r($arr); /* Output: Array ( [one] => a [three] => c [two] => b ) */ ?> |
2. Using array_combine() function
The following solution preserves the original order of keys in the array. The idea is to invoke array_keys() function to extract all the array keys into a separate array. Then, search the array for the old key and replace it with the new key. Finally, combine the keys of the extracted array with the values of the original array using the array_combine() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php $arr = array('one' => 'a', 2 => 'b', 'three' => 'c'); $old_key = '2'; $new_key = 'two'; if (array_key_exists($old_key, $arr)) { $keys = array_keys($arr); $old_key_index = array_search($old_key, $keys); $keys[$old_key_index] = $new_key; $new_arr = array_combine($keys, $arr); print_r($new_arr); } /* Output: Array ( [one] => a [two] => b [three] => c ) */ ?> |
That’s all about changing the key of an array element in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)