This question already has an answer here:
Assuming I have the following 3 PHP arrays:
$arr1 = [1,2,3,4]
$arr2 = [5,2,4,1]
$arr3 = [2,1,2,2]
What's the most efficient built-in way that PHP has to add these arrays to elements in the same index of each array. Meaning, the final output would be the following:
$final = [8,5,9,7]
There should be an easier way than doing final = [$arr1[0]+$arr2[0]+$arr3[0]..]
etc. Also, I need to assume there's a variable amount of arrays, so hard coding the math like above isn't correct.
</div>
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)
}
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
Use foreach loop
$final = [];
foreach ( $arr1 as $key => $value) {
$final[] = (int)$value + (int)$arr2[$key] + (int)$arr3[$key];
}