Distinct Roles: array_map, array_walk, and array_filter
While array_map, array_walk, and array_filter all involve passing a callback function to operate on an array, they differ in their core functionality.
array_map excels at transforming array elements. It maps the callback's output onto a new array of the same length as the largest input array. Unlike array_walk, array_map maintains the original array's values unaltered.
array_walk specializes in modifying array elements in-place. It iterates over the array, invoking the callback for each element and allowing for key access. array_walk alters the input array directly, a feature array_map lacks.
array_filter selectively retains elements based on the callback's truthiness check. It prunes the input array, creating a new one that contains only the elements that pass the filter. array_filter preserves keys, unlike array_map, but unlike array_walk, it doesn't modify the original array.
Example:
<code class="php">$array = [2.4, 2.6, 3.5]; $mapResult = array_map('floor', $array); // Stays the same print_r($mapResult); // [2, 2, 3] array_walk($array, function (&$v, $k) { $v = floor($v); }); // Alters the array print_r($array); // [2, 2, 3] $filterResult = array_filter($array, function ($v) { return $v > 2.5; }); // Preserves keys print_r($filterResult); // [2.6, 3.5]</code>
The above is the detailed content of How Do `array_map`, `array_walk`, and `array_filter` Differ in Their Array Manipulation Techniques?. For more information, please follow other related articles on the PHP Chinese website!