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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…