Skip to content

Instantly share code, notes, and snippets.

@lopar
Created October 19, 2023 22:08
Show Gist options
  • Save lopar/dc400dcb218d175405d51e7e7ea2b799 to your computer and use it in GitHub Desktop.
Save lopar/dc400dcb218d175405d51e7e7ea2b799 to your computer and use it in GitHub Desktop.
Get sum of multiple array values with same keys.
<?php
function sumArrays (array ...$a): array
{
foreach ($a as $arr) {
if (!empty($merged)){
$arr = array_flip(array_keys($merged+$arr));
}
$merged = $arr;
}
$result = array_fill_keys(array_flip($merged),0);
foreach ($a as $arr) {
foreach ($arr as $k=>$v) {
$result[$k] += $v;
}
}
return $result;
}
$z = sumArrays(['1a'=>10,'2a'=>20],['2a'=>30,'3a'=>40],['3a'=>50,'4a'=>60],['a'=>2]);
/*
Array
(
[1a] => 10
[2a] => 50
[3a] => 90
[4a] => 60
[a] => 2
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment