How to Change/ Replace Array Key Name in PHP Associative Array?

02-11-2020
PHP

We can change the array key name of an associative array in PHP easily.

Replace Array Key in PHP Associative Array

Here I’m using the below function to replace the key name of associative arrays in my project.

<?php
function array_key_replace($item, $replace_with, array $array){
    $updated_array = [];
    foreach ($array as $key => $value) {
        if (!is_array($value) && $key == $item) {
            $updated_array = array_merge($updated_array, [$replace_with => $value]);
            continue;
        }
        $updated_array = array_merge($updated_array, [$key => $value]);
    }
    return $updated_array;
}

Here is how you can use the above function.

<?php
$my_array = array(
    "first_name" => "Adeeb",
    "last_name" => "C",
    "age" => "25"
);
$new_array = array_key_replace('last_name', 'sure_name', $my_array);

print_r($new_array);

And, now by running the above snippet we get the following output.