Home >Backend Development >PHP Tutorial >How Do `array_map`, `array_walk`, and `array_filter` Differ in Their Array Manipulation Techniques?

How Do `array_map`, `array_walk`, and `array_filter` Differ in Their Array Manipulation Techniques?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 04:22:03981browse

 How Do `array_map`, `array_walk`, and `array_filter` Differ in Their Array Manipulation Techniques?

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 (&amp;$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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn