Home>

Closures are also called anonymous functions introduced in php5.3.

Instructions

Need to adjust values ​​in array elements

$data=range (0, 100);//You want to add the value of each element.
suffix of html
$suffix=".html";
</p>
<p>
function makesuffix ($str, $suffix)
{
 return $str. $suffix;
}
</p>
<p>
$new_data=array_map (function ($item) use ($suffix) {
 return makesuffix ($item, $suffix);
}, $data);

Need to change the structure of the element

$arr=[
 [
 "id" =>"", "name" =>"", "create_time" =>"", ],];
</p>
<p>
$new_data=array_map (function ($item) {
 return ["id" =>$item ["id"], "name" =>$item ["name"]];
}, $arr);
//If you use foreach, you need to create a zero-time variable in the loop.
Assign the required value to this variable

effectiveness

$data=range (0, 50000)
//1
foreach ($data as & $value) {
 $value=makesuffix ($value, $suffix);
}
</p>
<p>
//2
foreach ($data as $value) {
 $new []=makesuffix ($value, $suffix);
}
</p>
<p>
//3
array_map (function ($item) use ($suffix) {
 return makesuffix ($item, $suffix);
}, $data);

After 5w executions,Looking at the results from 1-3, in most cases, the execution time increases sequentially.One execution result time is as follows

1:0.0260009765625
2:0.038002014160156
3:0.047003030776978

in conclusion

Closure code is relatively elegant,But the logic is more confusing,Relatively inefficient compared to other methods,Use with caution. It is recommended that the code structure is relatively messy.Use when packaging is required.

php
  • Previous Nginx backslash automatic decoding problem solution
  • Next Small Drupal database backup and large site MySQL backup strategy sharing