What are standard array functions like array_map and array_filter, and how do they differ in purpose?
Last updated
Both are higher-order array functions, but they serve different purposes: array_map transforms every element, while array_filter selects a subset based on a predicate.
array_map:Applies a callback to each element and returns a new array of the same length with transformed values.
Can iterate multiple arrays in parallel.
array_filter:Keeps only elements for which the callback returns truthy, preserving original keys.
With no callback it removes falsy values.
Related:
array_reducecollapses an array to a single value.Note:
array_filterpreserves keys (you may needarray_valuesto reindex), whereasarray_mapreindexes when mapping a single array.
[lang:php]
$nums = [1, 2, 3, 4];
array_map(fn($n) => $n * 2, $nums); // [2, 4, 6, 8]
array_filter($nums, fn($n) => $n % 2 === 0); // [1 => 2, 3 => 4]