65

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?

Emile Bergeron
  • 16,148
  • 4
  • 74
  • 121
Breno Gazzola
  • 2,012
  • 1
  • 16
  • 36

2 Answers2

165

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);
mfonda
  • 7,663
  • 1
  • 25
  • 30
  • Thanks a lot mfonda, I took a look at the manual page but missed that keyword in the code example. – Breno Gazzola Jan 04 '11 at 11:48
  • you saved my day ! simple and usefull <3 – Shahrokhian Mar 09 '14 at 08:50
  • 20
    Just to add to the above answer, the parent scope variable are being COPIED rather than being made available inside the callback function. If the parent parameter needs to be manipulated, a reference should be sent like so `$listOfValLessThanAvg = []; $callback = function($val) use ($avg, &$listOfValLessThanAvg) { if( $val < $avg) array_push($listOfValLessThanAvg, $val); };` – pravin Jun 01 '15 at 07:23
  • Racking my brains on how to do this. First thought was `$GLOBALS` but obviously that's a no go. Came across this answer. Literally perfect. – JustCarty Oct 09 '17 at 15:51
-7

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);
Viper_Sb
  • 1,759
  • 13
  • 18