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:

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:

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:

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:

Here is an example of the replaceArrayKey function being used:

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!

Facebook Comments