For a sleek, functional-style snippet, use array_map()
to "transpose" the rows of data. This means that columns of data will be passed to the custom function. From there, perform the averaging math.
Code: (Demo)
$array1 = [0, 7, 5, 0];
$array2 = [2, 6, 10, 0];
$array3 = [4, 8, 15, 10];
$array4 = [6, 7, 20, 10];
var_export(
array_map(
fn() => array_sum(func_get_args()) / func_num_args(),
$array1,
$array2,
$array3,
$array4
)
);
// fn(...$col) => array_sum($col) / count($col), would also work
Output:
array (
0 => 3,
1 => 7,
2 => 12.5,
3 => 5,
)
Note, this technique will fill gaps in the columns with null
(counting as 0
) when arrays are not all of the same length: Demo.
If your input array was a single multi-dimensional array, you could use the spread operator to unpack it into array_map()
.
var_export(array_map(fn() => array_sum(func_get_args()) / func_num_args(), ...$arrays));
To prevent null
values from skewing the calculations, filter them before doing the math: Demo.
var_export(
array_map(
fn(...$col) => array_sum($col) / count(array_filter($col, fn($v) => !is_null($v))),
...$arrays
)
);
// or: fn(...$col) => array_sum($col) / count(array_diff($col, ['']))