Skip to content
Advertisement

replace array keys with given respective keys

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.

Advertisement

Answer

array_combine(array_merge($old, $keyReplaceInfoz), $old)

I think this looks easier than what you posed.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement