How To Change Array Key In Php

In this tutorial, we will discuss how to change array keys in PHP. Sometimes, you may need to rename or change the key of an associative array in your PHP application. There is no built-in function to change array keys directly in PHP, but using a combination of existing functions and a bit of custom code, we can achieve this easily.

Using array_combine() and array_values() functions

We can use the array_combine() and array_values() functions to change the keys of an associative array. The array_combine() function accepts two arrays as arguments, an array of keys and an array of values, and combines them into a new associative array. The array_values() function returns an indexed array containing the values of the input array.

Here’s an example of how to use these functions to change the key of an array:

$array = [
    'old_key' => 'value',
];

$new_key = 'new_key';

$array = array_combine(
    [$new_key],
    array_values($array)
);

print_r($array);

In this example, we’ve successfully changed the key ‘old_key’ to ‘new_key’ while keeping the value intact. The output will be:

Array
(
    [new_key] => value
)
    

Custom function to change array key

Alternatively, you can create a custom function to change the key of an array. Here’s an example of how to do this:

function change_key($array, $old_key, $new_key)
{
    if (!array_key_exists($old_key, $array)) {
        return $array;
    }

    $keys = array_keys($array);
    $keys[array_search($old_key, $keys)] = $new_key;

    return array_combine($keys, $array);
}

$array = [
    'old_key' => 'value',
];

$array = change_key($array, 'old_key', 'new_key');

print_r($array);

This custom function, named change_key(), accepts an array and two keys as arguments. It first checks if the old key exists in the array. If it does, the function replaces the old key with the new key and combines the modified keys array with the original array’s values.

In this example, we’ve also successfully changed the key ‘old_key’ to ‘new_key’ while keeping the value intact. The output will be:

Array
(
    [new_key] => value
)
    

Conclusion

Changing array keys in PHP can be achieved using a combination of built-in functions or by creating a custom function. Both of these methods allow you to change keys easily while preserving the original values of the array. Choose the method that best suits your needs and don’t hesitate to customize these examples for your own application.