0

I have an array and I want to make the average of its array element.

$array = array(
               '1' => array('1', '2'), 
               '2' => array('3', '7'), 
               '3' => array('5', '6'));

function average($arr)
    { if (!is_array($arr)) return false;
    return array_sum($arr)/count($arr); }

array_walk($array, 'average');
print_r($array);

The problem is that my function is not applied by array_walk. I got the exact same array I declared.

2 Answers 2

2

Try

function average($elem){
   return array_sum($elem)/sizeof($elem);
}               
$arr = array_map('average',$array);

See demo here

Sign up to request clarification or add additional context in comments.

1 Comment

Short, quick, working well and a live demo. Thanks a lot
0

you are returning the values from average function but not receiving it anywhere, if you wana change the multidimensional arrays values to their sum do this:

function average(&$arr)//&
{ 
    if (!is_array($arr)) return false;
    $arr = array_sum($arr)/count($arr); 
}

1 Comment

I have already tried this solution and the result is the same

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.