1

I try to pass a key of an array in parameter in my function like that

function getStats($array , $key){ $data = array_sum(array_map(function($item) { return $item[$key]; }, $array)); return $data; } $stats = getStats($myarray , 'nb_view'); 

It doesn't work but this works

function getStats($array){ $data = array_sum(array_map(function($item) { return $item['nb_view']; }, $array)); return $data; } $stats = getStats($array); 
1
  • please post array over here: Commented Jun 10, 2016 at 9:41

1 Answer 1

5

When defining your anonymous function, the use keyword allows you to inherit variables from the parent scope.

function getStats($array , $key){ $data = array_sum(array_map(function($item) use($key) { return $item[$key]; }, $array)); return $data; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.