使用变量计算出的外部回调函数
您有一个数组$ arr,想要使用array_filter创建一个新的数组,该数组仅包含小于$ arr中元素的平均值的新数组。使用回调函数实现此功能,您可能会遇到函数的挑战,即在函数内部和使用其内部的平均值来挑战。但是,使用关键字提供了一个解决方案。使用键字允许匿名函数从父范围继承变量。在这种情况下,您可以按以下方式定义回调函数:
在这里,$ avg是使用use关键字从父范围继承的。回调函数现在可以使用$ avg来过滤元素。[php 7.4或ling flow php 7.4或以后)
You can define the callback function as follows:
$callback = fn($val) => $val
Simplified Array Filtering with Arrow Functions
Since arrow functions are highly concise, you can embed them directly within the array_filter call:
$avg = array_sum($arr) / count($arr); $callback = function($val) use ($avg) { return $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 运营。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3