I\'m trying to merge/sums 2 arrays that can contain integers or more arrays (themselves containing integer).
When the values are integers, I need to sum them in the
You can get all the keys for the foreach loop, live demo.
Note, you also can check if a key of any array is undefined, then save the defined value for the key.
function sumArrayValues($array1, $array2)
{
$keys = array_keys($array1 + $array2);
foreach ($keys as $key)
{
if (is_array($array1[$key]) || is_array($array2[$key]))
$array1[$key] = sumArrayValues($array1[$key], $array2[$key]);
else
@$array1[$key] = (int)$array1[$key] +(int)$array2[$key];
}
return $array1;
}