Callback function using variables calculated outside of it

Breno Gazzola picture Breno Gazzola · Jan 3, 2011 · Viewed 26.9k times · Source

Basically I'd like to do something like this:

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$avg = array_sum($arr) / count($arr);
$callback = function($val){ return $val < $avg };

return array_filter($arr, $callback);

Is this actually possible? Calculating a variable outside of the anonymous function and using it inside?

Answer

mfonda picture mfonda · Jan 3, 2011

You can use the use keyword to inherit variables from the parent scope. In your example, you could do the following:

$callback = function($val) use ($avg) { return $val < $avg; };

For more information, see the manual page on anonymous functions.