Change key in associative array in PHP

You could have:

  1. an array that maps the key exchange (to make the process parametrizable)
  2. a loop the processes the original array, accessing to every array item by reference

E.g.:

$array = array( array('n'=>'john','l'=>'red'), array('n'=>'nicel','l'=>'blue') );

$mapKeyArray = array('n'=>'name','l'=>'last_name');

foreach( $array as &$item )
{
    foreach( $mapKeyArray as $key => $replace )
    {
        if (key_exists($key,$item))
        {
            $item[$replace] = $item[$key];
            unset($item[$key]); 
        }
    }
}

In such a way, you can have other replacements simply adding a couple key/value to the $mapKeyArray variable.

This solution also works if some key is not available in the original array


Something like this maybe:

if (isset($array['n'])) {
    $array['name'] = $array['n'];
    unset($array['n']);
}

NOTE: this solution will change the order of the keys. To preserve the order, you'd have to recreate the array.


Using array_walk

array_walk($array, function (& $item) {
   $item['new_key'] = $item['old_key'];
   unset($item['old_key']);
});