Closure is also called anonymous function and was introduced in PHP5.3.
How to use
Need to adjust the values in the array elements
function makeSuffix($str, $suffix)
{
Return $str . $suffix;
}
$new_data = array_map(function($item) use ($suffix) {
Return makeSuffix($item, $suffix);
}, $data);
Need to change the structure of the element
$new_data = array_map(function($item) {
Return ['id'=>$item['id'],'name'=>$item['name']];
}, $arr);
//If you are using foreach, you need to create a zero-time variable in the loop and assign the required value to this variable
Execution efficiency
//2
foreach ($data as $value) {
$new[] = makeSuffix($value, $suffix);
}
//3
array_map(function($item) use ($suffix) {
Return makeSuffix($item, $suffix);
}, $data);
Conclusion
The closure code is relatively elegant, but the logic is easy to confuse, and its execution efficiency is relatively low compared to other methods, so it should be used with caution. It is recommended to use it when the code structure is messy and needs to be encapsulated.
I hope this article can help students who have never used it or have questions about PHP closures. If there is something wrong, please feel free to comment.