Replace Array Keys in PHP

If you want to replace the keys in an array there is no native php function that does this currently. So I wrote one. It takes the keys from the first array and replaces it with a new key. See code snippet below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Changes the keys of an array by matching the keys of both arrays and changes to the value
* @return array
*
* Example Usage:
* $ary1 = array('myBadKey' => 1, 2, 'foo' => bar);
* $ary2 = array('myBadKey' => 'myGoodKey', 0 => 'NonNumericKey');
* print_r(array_key_merge($ary1, $ary2));
*/

function array_key_merge($array1, $array2)
{
foreach($array2 as $key => $value)
{
if(array_key_exists($key, $array1))
{
$array1[$array2[$key]] = $array1[$key];
unset($array1[$key]);
}
}

return $array1;
}