Analysis of closures (anonymous functions) in PHP and php. The closure (anonymous function) in PHP is also called the anonymous function PHP5.3. The code for copying the values in the array elements should be adjusted as follows: $ closure (anonymous function) analysis in datarang PHP, php analysis
The closure is also called the introduction of the anonymous function PHP5.3.
Usage
You need to adjust the value in the array element.
The code is as follows:
$ Data = range (0,100); // add the suffix of .html to the values of every element
$ Suffix = '.html ';
Function makeSuffix ($ str, $ suffix)
{
Return $ str. $ suffix;
}
$ New_data = array_map (function ($ item) use ($ suffix ){
Return makeSuffix ($ item, $ suffix );
}, $ Data );
Element structure needs to be changed
The code is as follows:
$ Arr = [
[
'Id' => '',
'Name' => '',
'Create _ time' => '',
],
];
$ New_data = array_map (function ($ item ){
Return ['id' => $ item ['id'], 'name' => $ item ['name'];
}, $ Arr );
// If foreach is used, you also need to create a zero-time variable in the loop and assign the required value to this variable.
Execution efficiency
The code is as follows:
$ Data = range (0, 50000)
// 1
Foreach ($ data as & $ value ){
$ Value = makeSuffix ($ value, $ suffix );
}
// 2
Foreach ($ data as $ value ){
$ New [] = makeSuffix ($ value, $ suffix );
}
// 3
Array_map (function ($ item) use ($ suffix ){
Return makeSuffix ($ item, $ suffix );
}, $ Data );
After executions, the results are 1-3. In most cases, the execution time Increases Sequentially. the execution result time is as follows:
The code is as follows:
1-0. 0260009765625
. 038002014160156
3: 0. 047003030776978
Conclusion
The code of the closure is relatively elegant, but the logic is more confusing. the execution efficiency is relatively low compared with other methods, so use it with caution. We recommend that you use it when the code structure is messy and needs to be encapsulated.
I hope this article will help students who have never used or have doubts about the closure of PHP, and if there is anything wrong, welcome to spend money.
For anonymous function analysis, php analysis closure is also called Anonymous function PHP5.3. The code for adjusting the value in the array element is as follows: $ data = rang...