Skip to content
array_map, array_filter, array_reduce
step 1/5

Reading — step 1 of 5

Learn

~1 min readArrays

PHP's functional array helpers:

$nums = [1, 2, 3, 4, 5];

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

$evens = array_filter($nums, fn($n) => $n % 2 === 0);
// [2, 4]   — but keys are preserved! [1 => 2, 3 => 4]

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

A gotcha: array_filter preserves keys. To get a fresh 0-indexed array, wrap with array_values():

$evens = array_values(array_filter($nums, fn($n) => $n % 2 === 0));
// [2, 4]   — re-indexed [0 => 2, 1 => 4]

For more, see array_walk (mutate in place), array_combine (zip keys with values), array_flip (swap keys and values), array_unique (dedupe).

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

array_map, array_filter, array_reduce — PHP Fundamentals