June 5, 2025

How do array_map(), array_filter(), and array_reduce() work?

These are functional-style tools that work with arrays:

๐Ÿ”ธ array_map()

  • Applies a callback to each element, returning a new array.
$nums = [1, 2, 3];
$squared = array_map(fn($n) => $n * $n, $nums);
// [1, 4, 9]

๐Ÿ”ธ array_filter()

  • Filters elements based on a condition, keeping those that return true.
$nums = [1, 2, 3, 4];
$even = array_filter($nums, fn($n) => $n % 2 == 0);
// [2, 4]

๐Ÿ”ธ array_reduce()

  • Reduces an array to a single value using a callback.
$nums = [1, 2, 3];
$sum = array_reduce($nums, fn($carry, $item) => $carry + $item, 0);
// 6

๐Ÿ“Œ Interview Tip: Be ready to use these for clean, concise logic โ€” like filtering user input, transforming arrays, or computing totals.

Summary Table:


FunctionReturnsPreserves KeysOutput Shape
array_map()Array (same size)โŒTransformed array
array_filter()Filtered arrayโœ…Subset of input
array_reduce()Single value (any type)N/AOne result