SyntaxStudy
Sign Up
PHP array_map, filter & reduce
PHP Beginner 1 min read

array_map, filter & reduce

Functional Array Operations

array_map()

Apply a callback to each element. Returns a new array.

array_filter()

Keep only elements where callback returns true.

array_reduce()

Reduce array to a single value using a callback.

Example
<?php
$nums = [1, 2, 3, 4, 5];

// array_map
$doubled = array_map(fn($n) => $n * 2, $nums);
// [2, 4, 6, 8, 10]

// array_filter (keeps truthy by default)
$evens = array_filter($nums, fn($n) => $n % 2 === 0);
// [2, 4]

// array_reduce
$sum = array_reduce($nums, fn($carry, $n) => $carry + $n, 0);
// 15

// Chained with arrow functions
$result = array_reduce(
    array_filter($nums, fn($n) => $n > 2),
    fn($sum, $n) => $sum + $n,
    0
); // 12
?>