74

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?

2 Answers 2

187

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot mfonda, I took a look at the manual page but missed that keyword in the code example.
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); };
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.
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.
-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);

2 Comments

Global variables are considered bad practice. Moreover, using global vars here is an overkill, since use is suffice.
Global variables are evil!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.