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.

Download  Run Code

 
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.

Download  Run Code

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.

Download  Run Code

That’s all about changing the key of an array element in PHP.