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:
Function | Returns | Preserves Keys | Output Shape |
---|---|---|---|
array_map() | Array (same size) | β | Transformed array |
array_filter() | Filtered array | β | Subset of input |
array_reduce() | Single value (any type) | N/A | One result |
Comments are closed.