Wistar
Wistar

Reputation: 3790

Array_walk average with multidimensional array

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.

Upvotes: 0

Views: 757

Answers (2)

Exlord
Exlord

Reputation: 5371

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

Upvotes: 0

Nouphal.M
Nouphal.M

Reputation: 6344

Try

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

See demo here

Upvotes: 2

Related Questions