3 Ways to Change Array Key without Changing the Order in PHP

Change Array Key without Changing the Order in PHP

You can change array key too easily but doing it without changing the order in PHP is quite tricky. Simply assigning the value to a new key and deleting old one doesn’t change the position of the new key at the place of old in the array.

So in this article, I have explained 3 ways to let you change array key while maintaining the key order and last one of them can be used with a multidimensional array as well. But before that, if you just need to rename a key without preserving the order, the two lines code does the job:

 

Change Array Key using JSON encode/decode

It’s short but be careful while using it. Use only to change key when you’re sure that your array doesn’t contain value exactly same as old key plus a colon. Otherwise, the value or object value will also get replaced.

 

2. Replace key & Maintain Order using Array Functions in PHP

The functionreplace_key() first checks if old key exists in the array? If yes then creates an Indexed Array of keys from source array and change old key with new using PHP array_search() function.

Finally, array_combine() function returns a new array with key changed, taking keys from the created indexed array and values from source array. The non-existence of old key just simply returns the array without any change.

 

3. Change Array Key without Changing the Order (Multidimensional Array Capable)

This solution is quite elegant and can work with multidimensional array too with help of classic PHP loop and recursive function call. Let’s see how are we doing this change.

Here we need to pass two arrays in the function call (Line #18). The first parameter is the array which needs to change keys and another is an array containing indexes as old keys and values as new keys. Upon execution, the function will change all the keys in the first array which are present in the second array too and their respective values will be new keys.

The recursive calling within function ensures changing keys up to the deepest branch of the array. The functionrecursive_change_key() here is provided along with the example to understand better.

Don’t forget to read our extensive list of 38 PHP related tutorials yet.

So here you got 3 ways to change array key without changing the order of array in PHP. And the last one works with a multidimensional array as well. All you need is just to provide correct set of “old key, new key” pairs for changing purpose.

You Might Interested In