I have an array that consists of names of people and their height. I need to find the average height using the function array_reduce which is wrapped in a function assigned to a variable. Below is the code I wrote so far. Everything seems to be working until I pass the array to the array_reduce function which is then NULLed. I tried to explain it with comments in the code. Why is the array suddenly deleted and how do I pass it to the most inner function?
$people = [
['name'=> 'John' , 'height'=> 1.65],
['name'=> 'Peter' , 'height'=> 1.85],
['name'=> 'Silvia', 'height'=> 1.69],
['name'=> 'Martin', 'height'=> 1.82]
];
$filter = function ($people)
{
$averageHeight = 0;
$count = count($people);
echo $count;
//if I var_dump($people) - the array $people is FINE.
return array_reduce(
$people,
function ($people) use (&$averageHeight, &$count)
{
$averageHeight += $people['height'] / $count;
return $averageHeight;
//var_dump($people); - var people is NULL. Where did it go?
}
);
};
print_r($filter($people));
$peopleis null is because it's the first function parameter you named people and not the actual array you declared above. PHP refers to this parameter as$carrywhich is the carried value. If you don't provide a default carry value it starts off as null.$averageHeight = array_sum(array_column($people, 'height')) / count($people);