3 Ways to 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 without Changing the Order in PHP

1. 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 #20). 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

14 COMMENTS

  1. Antman says:

    Method 2 will fail if you have mixed key with a 0 index, as array_search without the strict flag will match 0 to any non numerical stirng.
    I added a check for a numerical string and cast it to int:
    public function replace_key( array $array, $oldKey, $newKey ) : array
    {
    if ( ! array_key_exists( $oldKey, $array ) )
    {
    return $array;
    }

    $keys = array_keys( $array );

    if ( is_string( $oldKey ) && is_numeric( $oldKey ) && strpos( $oldKey, ‘.’ ) === false )
    {
    $oldKey = (int) $oldKey;
    }

    $keys[ array_search( $oldKey, $keys, true ) ] = $newKey;
    return array_combine( $keys, $array );
    }

    PHP Unit test ->
    public function testRenameKeyPreservingOrder() : void
    {
    $array = [
    ‘a’ => ‘ay’,
    0 => ‘zero’,
    ‘b’ => ‘be’,
    ‘1.1’ => ‘one point one’,
    ‘c’ => ‘ce’,
    3 => ‘three’,
    ];

    // Check nothing happens if the key isn’t present
    $this->assertSame( $array, \TGHelpers_Array::renameKeyKeepingOrder( $array, ‘foo’, ‘bar’ ) );

    // Check string keys
    $this->assertSame(
    [
    ‘a’ => ‘ay’,
    0 => ‘zero’,
    ‘buh’ => ‘be’,
    ‘1.1’ => ‘one point one’,
    ‘c’ => ‘ce’,
    3 => ‘three’,
    ],
    \TGHelpers_Array::renameKeyKeepingOrder( $array, ‘b’, ‘buh’ )
    );

    // Check “float” (string) keys
    $this->assertSame(
    [
    ‘a’ => ‘ay’,
    0 => ‘zero’,
    ‘b’ => ‘be’,
    ‘5’ => ‘one point one’,
    ‘c’ => ‘ce’,
    3 => ‘three’,
    ],
    \TGHelpers_Array::renameKeyKeepingOrder( $array, ‘1.1’, 5 )
    );

    // Check numerical
    $this->assertSame(
    [
    ‘a’ => ‘ay’,
    0 => ‘zero’,
    ‘b’ => ‘be’,
    ‘1.1’ => ‘one point one’,
    ‘c’ => ‘ce’,
    5 => ‘three’,
    ],
    \TGHelpers_Array::renameKeyKeepingOrder( $array, 3, 5 )
    );

    // Check numerical as string
    $this->assertSame(
    [
    ‘a’ => ‘ay’,
    0 => ‘zero’,
    ‘b’ => ‘be’,
    ‘1.1’ => ‘one point one’,
    ‘c’ => ‘ce’,
    5 => ‘three’,
    ],
    \TGHelpers_Array::renameKeyKeepingOrder( $array, ‘3’, 5 )
    );
    }

    Reply
    1. Amit Sonkhiya says:

      @ellisgl:disqus

      That’s good. Yet that piece of code requires more processing time as well as passing many parameters which isn’t less than memory occupied by the temporary array created here.

      Reply
    2. Amit Sonkhiya says:

      @ellisgl:disqus

      That’s good. Yet that piece of code requires more processing time as well as passing many parameters which isn’t less than memory occupied by the temporary array created here.

      Reply
        1. Amit Sonkhiya says:

          Serialization, regular expression and JSON string always have performance issue. Rest all are around near except the benchArrayKeys.

          Reply
  2. Klesk says:

    I think there is a typo
    Line 6 : it rather be

    $newArr[$key] = is_array($v) ? recursive_change_key($v, $set) : $v;

    because it’s recursive 😀

    Reply

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.