How to average multiple arrays into one in PHP?

For more dynamically usage lets say for example 6 arrays or more, you can use this code:

$all_arrays = [
    array(0, 7, 5, 0),
    array(2, 6, 10, 0),
    array(4, 8, 15, 10),
    array(6, 7, 20, 10),
    array(1, 2, 3, 4),
    array(5, 6, 7, 8),
    // more arrays
];

$each_array_count = count($all_arrays[0]); // 4
$all_arrays_count = count($all_arrays); // 6

$output = [];

for ($i = 0; $i < $each_array_count; $i++) {
    for ($j=0; $j < $all_arrays_count; $j++) { 
        $output[$i] += $all_arrays[$j][$i] / $all_arrays_count;        
    }
}

echo "<pre>";
var_dump($output);

Here is a simple solution but you can generalize it further and make it generic but it will work for now. It can be updated accordingly:

NOTE: Assuming the count of array are same as you have mentioned

     $result = [];
     for ($i = 0; $i < count($array1); $i++) {
         $result [] = ($array1[$i] + $array2[$i] + $array3[$i] + $array4[$i]) / count($array1);
     }
     dd($result);

Tags:

Php

Arrays