Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to average multiple arrays into one in PHP?

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);
like image 232
KarelRuzicka Avatar asked Feb 11 '21 18:02

KarelRuzicka


1 Answers

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)
}
like image 146
Pejman Kheyri Avatar answered Oct 05 '22 06:10

Pejman Kheyri