replace array keys with given respective keys

Maulik Vora picture Maulik Vora · Jul 30, 2012 · Viewed 27.5k times · Source

I have an array like below

$old = array(
       'a' => 'blah',
       'b' => 'key',
       'c' => 'amazing',
       'd' => array(
                0 => 'want to replace',
                1 => 'yes I want to'
              )
       );

I have another array having keys to replace with key information.

$keyReplaceInfoz = array('a' => 'newA', 'b' => 'newB', 'c' => 'newC', 'd' => 'newD');

I need to replace all keys of array $old with respective values in array $keyReplaceInfo.

Output should be like this

$old = array(
       'newA' => 'blah',
       'newB' => 'key',
       'newC' => 'amazing',
       'newD' => array(
                0 => 'want to replace',
                1 => 'yes I want to'
              )
       );

I had to do it manually as below. I am expecting better option. can anyone suggest better way to accomplish this?

$new = array();
foreach ($old as $key => $value)
{
     $new[$keyReplaceInfoz[$key]] = $value;
}

I know this can be more simpler.

Answer

Summoner picture Summoner · Jul 30, 2012
array_combine(array_merge($old, $keyReplaceInfoz), $old)

I think this looks easier than what you posed.