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