$arr = [
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
];
$arr2 = [
[1, 2, 3, 4],
[1, 2, 3, 4],
];
$arr3 = [
[1, 2, 3, 4]
];
$result = [
[3, 6, 9, 12],
[2, 4, 6, 8],
[1, 2 ,3 , 4]
];
function sumArrays(...$arrays) {
usort($arrays, fn($a, $b) => count($b) - count($a));
$biggest = $arrays[0];
$other = array_slice($arrays, 1);
$result = [];
foreach ($biggest as $rowIndex=>$row) {
$resultRow = [];
foreach ($row as $fieldIndex => $field) {
foreach ($other as $otherArray) {
if (array_key_exists($rowIndex, $otherArray)) {
$field += $otherArray[$rowIndex][$fieldIndex];
}
}
$resultRow[] = $field;
}
$result[] = $resultRow;
}
return $result;
}
var_dump(sumArrays($arr2, $arr3, $arr));