Make them all one array and use array_sum and array_column
$arr1 = [1,2,3,4];
$arr2 = [5,2,4,1];
$arr3 = [2,1,2,2];
$all = [$arr1, $arr2, $arr3];
foreach($all[0] as $key => $v){
$result[$key] = array_sum(array_column($all, $key));
}
var_dump($result);
Output:
array(4) {
[0]=>
int(8)
[1]=>
int(5)
[2]=>
int(9)
[3]=>
int(7)
}
https://3v4l.org/qndQH
This method will only work if all arrays are same length or the first is the longest.
If you have an unknown amount of arrays within an name range then you can loop and use isset to see if the array exist, if yes add it to $all.
$arr1 = [1,2,3,4,5];
$arr2 = [5,2,4,1];
$arr3 = [2,1,2,2];
$arr4 = [2,1,2,2];
$all = [];
$i=1;
while(isset(${"arr" . $i})){
$all[] = ${"arr" . $i};
$i++;
}
foreach($all[0] as $key => $v){
$result[$key] = array_sum(array_column($all, $key));
}
var_dump($result);
If you want it all super dynamic then you can use the code above and add what subarray is the longest and loop that in the last loop.
$arr1 = [1,2,3,4,5];
$arr2 = [5,2,4,1];
$arr3 = [2,1,2,2];
$arr4 = [2,1,2,2];
$arr5 = [2,1,2,2,6,1,3,2];
$all = [];
// Add all subarrays dynamically and see which is the longest
$i=1;
$count = Null;
while(isset(${"arr" . $i})){
$all[] = ${"arr" . $i};
if(count(${"arr" . $i}) > $count){
$count = count(${"arr" . $i});
$longkey = $i-1;
}
$i++;
}
// Loop the longest subarray
foreach($all[$longkey] as $key => $v){
$result[$key] = array_sum(array_column($all, $key));
}
var_dump($result);
Working example:
https://3v4l.org/lIVGo