使用變量計算出的外部回調函數
您有一個數組$ 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