Using Variables Calculated Outside Callback Functions
In PHP, it is possible to calculate variables outside of callback functions and use them within those functions. Let's consider the following scenario:
You have an array $arr and want to use array_filter to create a new array containing only values less than the average of the elements in $arr.
To achieve this using a callback function, you may encounter the challenge of calculating the average outside the function and using it within. However, the use keyword provides a solution.
Using the use Keyword
The use keyword allows anonymous functions to inherit variables from the parent scope. In this case, you can define the callback function as follows:
$avg = array_sum($arr) / count($arr); $callback = function($val) use ($avg) { return $valHere, $avg is inherited from the parent scope using the use keyword. The callback function can now use $avg to filter elements.
return array_filter($arr, $callback);Using Arrow Functions (PHP 7.4 or Later)
PHP 7.4 introduces arrow functions, which are more concise alternatives to anonymous functions. Arrow functions automatically capture outside variables, eliminating the need for use.
You can define the callback function as follows:
$callback = fn($val) => $valSimplified Array Filtering with Arrow Functions
Since arrow functions are highly concise, you can embed them directly within the array_filter call:
return array_filter($arr, fn($val) => $valIn summary, the use keyword or arrow functions allow you to calculate variables outside of callback functions and use them within, enabling more flexible and convenient filtering operations.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3