PHP: Replace an array key.

This is a beginners tutorial on how to replace an array key in PHP. In the guide below, I will also demonstrate how to replace a key in an associative array while preserving the array’s original order.

Replacing an array key.

Let’s start off by creating a simple PHP array:

//Example associative PHP array
$arr = array(
    'user_name' => 'John',
    'age' => 32,
    'nationality' => 'English'


If you var_dump the associative PHP array above, you will be given the following result:

Now, let’s say that you want to replace the key user_name with a new key called name. Firstly, you will need create the new key like so:

//Add the new key.
$arr['name'] = $arr['user_name'];


In the code above, we assigned the value of user_name to a new key called name. This leaves us with an array that looks like this:

As you can see, we now have two elements with the exact same value. This means that we can now delete the old key:

//Remove the old key.


Once you have removed the old key using PHP’s unset function, you will be left with the following array:

To sum it up: We ‘replaced’ the array key in question by assigning the element to a new key. Once the element was copied over, we were then able to remove the old key by using the unset function.

Replacing a key and preserving the order.

The code above does not preserve the original order of the array. As you probably noticed, the name of the person went from the top of the array to the bottom of the array. Although this won’t be a problem in the vast majority of cases, there could be scenarios where you need to replace an array key and preserve the original order.

In order to do this, you can use the custom PHP function below:

 * Replaces an array key and preserves the original
 * order.
 * @param $array The array in question.
 * @param $oldKey The key that you want to replace.
 * @param $newKey The name of the new key.
 * @return array
function replaceArrayKey($array, $oldKey, $newKey){
    //If the old key doesn't exist, we can't replace it...
        return $array;
    //Get a list of all keys in the array.
    $arrayKeys = array_keys($array);
    //Replace the key in our $arrayKeys array.
    $oldKeyIndex = array_search($oldKey, $arrayKeys);
    $arrayKeys[$oldKeyIndex] = $newKey;
    //Combine them back into one array.
    $newArray =  array_combine($arrayKeys, $array);
    return $newArray;

Here is an example of the replaceArrayKey function being used:

$arr = replaceArrayKey($arr, 'nationality', 'user_nationality');


In the PHP code above, I replaced the key nationality with a new array key called user_nationality. If you run the example for yourself, you should get the following result:

And as promised, the original order of the array was preserved!