Home  >  Q&A  >  body text

How to calculate the average of an array in PHP?

So I am in this array code

$numers = array
(
  array(198,208,109,11,636),
  array(198,188,84,55,756),
  array(194,206,113,13,531),
  array(184,213,127,18,101),
  array(194,213,127,23,110),
  array(984,213,127,44,125),
  array(184,213,127,88,980),
  array(995,211,129,63,888)
);

Now I want to calculate the column average of the second column (208, 188, 206, 213, 213, 213, 213, 211) (from the first 198, 198, 194, 184, 194, 984, 184, 995) and so on until the fifth to last column.

I don't know how to do this, so can someone explain to me how to calculate the column average for each column.

P粉345302753P粉345302753428 days ago462

reply all(1)I'll reply

  • P粉115840076

    P粉1158400762023-09-11 00:15:13

    <?php
    
    $numers = array(
      array(198,208,109,11,636),
      array(198,188,84,55,756),
      array(194,206,113,13,531),
      array(184,213,127,18,101),
      array(194,213,127,23,110),
      array(984,213,127,44,125),
      array(184,213,127,88,980),
      array(995,211,129,63,888)
    );
    
    $num_cols = count($numers[0]);
    
    for ($i = 0; $i < $num_cols; $i++) {
      $column = array_column($numers, $i); 
      $average = array_sum($column) / count($column);
      echo "Column $i average: $average<br>";
    }

    Output:

    Column 0 average: 391.375
    Column 1 average: 208.125
    Column 2 average: 117.875
    Column 3 average: 39.375
    Column 4 average: 515.875

    reply
    0
  • Cancelreply