0

I want to calculate the average of all the values of array based on key. i have an array like this

$res_arr = 
array 
{
array[0]=>array
{
    [0] => 3
            [1] => 7
            [2] => 9
            [3] =>3
            [4] => 22
}
array[1]=>array
{
    [0] => 5
            [1] => 5
            [2] => 8
            [3] => 9
            [4] => 0
}
array[2]=>array
{
    [0] => 10
            [1] => 5
            [2] => 8
            [3] => 7
            [4] => 3
}
....
....
....
....
array[100]
}

There are totally 5 elements in each array

it should return an array with average calculated as

$av_array = ();
$array  = array(6,5.6,8.3,6.3,8.3)

Below is the loop i used

foreach($res_arr as $m=>$val)
{
    //echo $val[0];
    $return[$val[$m]][] = $val;
    //$cnt++;

}
1
  • 1
    What problem you face in above loop? Commented Feb 4, 2014 at 9:22

3 Answers 3

4

Using array_map and array_sum:

function array_average($arr)
{
  return array_sum($arr)/count($arr);
}

$array = array_map("array_average", $input_array);
print_r($array);

Update: Alternative syntax:

$array_average = function($arr) {
    return array_sum($arr)/count($arr);
};
$array = array_map($array_average, $input_array);
print_r($array);
Sign up to request clarification or add additional context in comments.

2 Comments

Should $array_average be "array_average"?
@Class, yes, thanks for catching that, corrected answer.
0

Try this:

$av_array = [];
foreach($res_arr as $val)
{
    $av_array[] = array_sum($val)/count($val);
}
var_dump($av_array);

Comments

0

Do this way..

foreach($arr as $arr1)
    {
        foreach($arr1 as $k=>$v)
        {
            $sum_arr[]=$v;
        }
        echo $avg = array_sum($sum_arr)/count($sum_arr);
        unset($sum_arr);
    }
}

2 Comments

No thats wrong ,it should returm single array like this $array = array(6,5.6,8.3,6.3,8.3) 3+5+10/3 = 6.5 Ele,emt by element
Like what ? Do you want the averages in an array or you want it as an output ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.