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


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.

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]);
        $updated_array = array_merge($updated_array, [$key => $value]);
    return $updated_array;

Here is how you can use the above function.

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


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