7

Let's say I have 4 arrays with the same amount of values in each:

$array1 = array(0, 7, 5, 0);
$array2 = array(2, 6, 10, 0);
$array3 = array(4, 8, 15, 10);
$array4 = array(6, 7, 20, 10);

I want to count the average for all 4 of these arrays for each index. So I should get something like this:

array(3, 7, 12.5, 5);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
KarelRuzicka
  • 461
  • 2
  • 13

5 Answers5

3

Fully Dynamic Function:

I took on the task of building a fully dynamic function where you can input as many arrays as you want. I also added a null check as seen in the example below just in case you need to skip a value inside an array.

Function:

# Function takes in unlimited arrays,
# and returns the average of each index of 
# those arrays as a new array.
function arrayAverage(...$array){

    # Loop through the arrays in the input arguments.
    # For every array, extract all numeric values from each
    # element, and group them by index in a temporary
    # multi-dimensional array. If a value is null, or 
    # cannot be converted into an integer/float, skip it.
    foreach($array as $arr){
        for($i = 0; $i < count($arr); $i++){
            if(!is_null($arr[$i]) && ($arr[$i] == (int)$arr[$i]))
                $temparr[$i][] = (int)$arr[$i];
            elseif(!is_null($arr[$i]) && ($arr[$i] == (float)$arr[$i]))
                $temparr[$i][] = (float)$arr[$i];
        }
    }
        

    # Loop through the multi-dimensional array, 
    # and calculate the average of each.
    # Store results in a separate array to 
    # be returned after the loop is finished.
    for($j = 0; $j < count($temparr); $j++)
        $averages[] = array_sum($temparr[$j]) / count($temparr[$j]);
    
    # Return aforementioned array containing the averages. 
    return $averages;

}

Usage/Example:

# Arrays can have a different amount of key=>value pairs,
# and integer values stored as strings can be parsed,
# as shown in "$array2".
$array1 = array(0, 7, 5, 0);
$array2 = array(2, 6, 10, 0, "100");
$array3 = array(4, 8, 15, 10);
$array4 = array(6, 7, 20, 10);

# Example on how to skip values just in case the need arises
# (So averages won't be affected by having an extra number)
$array5 = array(null, null, null, null, 300);

$averages = arrayAverage($array1, $array2, $array3, $array4, $array5);
print_r($averages);

Output:

Array
(
    [0] => 3
    [1] => 7
    [2] => 12.5
    [3] => 5
    [4] => 200
)

Live Sandbox Demo:

https://onlinephp.io/c/bb513

Crimin4L
  • 610
  • 2
  • 8
  • 23
3

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);

Output: (Demo)

Warning: Undefined array key 0 in /in/E783F on line 20

Warning: Undefined array key 1 in /in/E783F on line 20

Warning: Undefined array key 2 in /in/E783F on line 20

Warning: Undefined array key 3 in /in/E783F on line 20
<pre>array(4) {
  [0]=>
  float(3)
  [1]=>
  float(6)
  [2]=>
  float(10)
  [3]=>
  float(5.333333333333333)
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Pejman Kheyri
  • 4,044
  • 9
  • 32
  • 39
2

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);
dev_mustafa
  • 1,042
  • 1
  • 4
  • 14
  • Close, but what about the case when there are 3 elements per array? Have a look at `/ count($array1)` – SirPilan Feb 11 '21 at 21:41
  • You can generalize it according to your need. I have mentioned in the answer that it can be further improved. If each array has 3 elements then `count($array1)` will work. – dev_mustafa Feb 12 '21 at 16:03
  • No, your calculation would end up in for example: `(1+1+1+1) / 3`, which is no longer the average. – SirPilan Feb 12 '21 at 16:50
  • Yes, I have mentioned that assuming both the number of arrays and each element in array are same. – dev_mustafa Feb 12 '21 at 16:54
1

Another approach:

$arrays = [$array1, $array2, $array3, $array4];

$result = [];
for ($i = 0; $i < count($array1); $i++) {
    $result[] = array_sum(array_column($arrays, $i)) / count($arrays);
}

Working example.

SirPilan
  • 4,649
  • 2
  • 13
  • 26
0

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, ['']))
mickmackusa
  • 43,625
  • 12
  • 83
  • 136