- Change values:
array_map cannot change values inside input arrays as long as array_walk can; in particular, array_map never changes its arguments.
Access to access keys:
array_map cannot work with array keys, array_walk can.
- Return value:
array_map returns a new array, array_walk returns true/false . Therefore, if you do not want to create an array as a result of traversing a single array, you must use its array_walk .
- Iteration of several arrays:
array_map can also take an arbitrary number of arrays, and it can array_walk through them in parallel, and array_walk works only on one.
- Send arbitrary data to the callback:
array_walk can get an additional arbitrary parameter to send a callback. It basically doesn't matter with PHP 5.3 (when anonymous functions were introduced).
- The length of the returned array:
- The resulting array
array_map has the same length as the largest input array; array_walk does not return an array, but at the same time it cannot change the number of elements in the original array; array_filter selects only a subset of the elements of an array according to the filtering function. He keeps the keys.
Example:
<pre> <?php $origarray1 = array(2.4, 2.6, 3.5); $origarray2 = array(2.4, 2.6, 3.5); print_r(array_map('floor', $origarray1)); // $origarray1 stays the same // changes $origarray2 array_walk($origarray2, function (&$v, $k) { $v = floor($v); }); print_r($origarray2); // this is a more proper use of array_walk array_walk($origarray1, function ($v, $k) { echo "$k => $v", "\n"; }); // array_map accepts several arrays print_r( array_map(function ($a, $b) { return $a * $b; }, $origarray1, $origarray2) ); // select only elements that are > 2.5 print_r( array_filter($origarray1, function ($a) { return $a > 2.5; }) ); ?> </pre>
Result:
Array ( [0] => 2 [1] => 2 [2] => 3 ) Array ( [0] => 2 [1] => 2 [2] => 3 ) 0 => 2.4 1 => 2.6 2 => 3.5 Array ( [0] => 4.8 [1] => 5.2 [2] => 10.5 ) Array ( [1] => 2.6 [2] => 3.5 )
A source