Callback function using variables calculated outside of it

PhpAnonymous Function

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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.

If you're running PHP 7.4 or later, arrow functions can be used. Arrow functions are an alternative, more concise way of defining anonymous functions, which automatically capture outside variables, eliminating the need for use:

$callback = fn($val) => $val < $avg;

Given how concise arrow functions are, you can reasonably write them directly within the array_filter call:

return array_filter($arr, fn($val) => $val < $avg);

Solution 2 - Php

use global variables i.e $GLOBAL['avg']

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

$return array_filter($arr, $callback);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBreno GazzolaView Question on Stackoverflow
Solution 1 - PhpmfondaView Answer on Stackoverflow
Solution 2 - PhpViper_SbView Answer on Stackoverflow