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

November 2, 2020

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.

About Author
Adeeb C (233 Articles)

Adeeb C is a Web Designer, Web Application Developer, Android App Developer, WordPress Developer, Professional Blogger. He has 5 years of experience in WordPress, Web Developing, Professional Blogging, and 2 years of experience in Android App Developing.