+ 1
array_map has no collateral effects while array_walk can; in particular, array_map never changes its arguments. array_map cannot operate with the array keys, array_walk can. array_map returns an array, array_walk only returns true/false. Hence, if you don't want to create an array as a result of traversing one array, you should use array_walk. array_map also can receive an arbitrary number of arrays, while array_walk operates only on one. array_walk can receive an extra arbitrary parameter to pass to the callback. This mostly irrelevant since PHP 5.3 (when anonymous functions were introduced). The resulting array of array_map/array_walk has the same number of elements as the argument(s); array_filter picks only a subset of the elements of the array according to a filtering function. It does preserve 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 )
15th Dec 2016, 9:28 AM
TechBeat
TechBeat - avatar