Home > Article > Backend Development > Xin Xing briefly analyzes the connection and difference between array_walk and array_map array walk class array walk trim array walk anonymous function
Let’s take a look at the specific usage of these two functions. The first is array_walk, the code is as follows:
<?php $arr = array(2,4,5,6,7); function xin(&$val,$key){ $val = $val*$val; } array_walk($arr, "xin"); var_dump($arr);The output content is as follows:
array (size=5) 0 => int 4 1 => int 16 2 => int 25 3 => int 36 4 => int 49As for array_map, let’s also give an example :
<?php function xin($a,$b){ return $a*$b; } $arr = array(2,3,4,5); $brr = array(5,6,7,8); $crr = array_map("xin",$arr,$brr); var_dump($crr);The output is as follows:
array (size=4) 0 => int 10 1 => int 18 2 => int 28 3 => int 40
We can find that for example, traversing an array, both functions can be implemented, but generally speaking, their focus is different:
(1)array_map can traverse n arrays at the same time, while array_walk usually traverses one.
(2)array_map must have a return value, because its return value needs to form a new array. But array_walk is usually not necessary, because its usual use is to change the original data.
(3)array_map usually has a role of data, but array_walk does not recommend deleting or adding data, only recommends modifying the value.
Of course, they can achieve the same function in some cases. The two are not distinct, but have certain intersections.
The above introduces Xin Xing's brief analysis of the connection and difference between array_walk and array_map, including the content of array and walk. I hope it will be helpful to friends who are interested in PHP tutorials.