70

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
  • 17,074
  • 5
  • 83
  • 129
Breno Gazzola
  • 2,092
  • 1
  • 16
  • 36

2 Answers2

175

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,873
  • 1
  • 26
  • 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
  • 21
    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
  • Memory wise, which is more efficient? I remember that in Javascript, an arrow function will be instantiated at each call, whereas an anonymous one is created once and recalled for each iteration/calls, something like that, which means arrow function is less efficient albeit more practical. Is it also the case in PHP? I feel like I should post this as a separate question, although I don't think it's the case in PHP. – Clockwork Dec 02 '22 at 10:28
-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,809
  • 14
  • 18