How to use array_map/array_filter/array_reduce in PHP

An important set of looping structures, often used in functional programming, is the set of array_map() / array_filter() / array_reduce().

Those 3 built-in PHP functions take an array, and a callback function that in each iteration takes each item in the array.

array_map() returns a new array that contains result of running the callback function on each item in the array:

$numbers = [1, 2, 3, 4];
$doubles = array_map(fn($value) => $value * 2, $numbers);

//$doubles is now [2, 4, 6, 8]

array_filter() generates a new array by only getting the items whose callback function returns true:

$numbers = [1, 2, 3, 4];
$even = array_filter($numbers, fn($value) => $value % 2 === 0)

//$even is now [2, 4]

array_reduce() is used to reduce an array to a single value.

For example we can use it to multiply all items in an array:

$numbers = [1, 2, 3, 4];

$result = array_reduce($numbers, fn($carry, $value) => $carry * $value, 1)

Notice the last parameter, it’s the initial value. If you omit that, the default value is 0 but that would not work for our multiplication example.

Note that in array_map() the order of the arguments is reversed, first you have the callback function and then the array. This is because we can pass multiple arrays using commas (array_map(fn($value) => $value * 2, $numbers, $otherNumbers, $anotherArray);). Ideally we’d like more consistency, but that’s what it is.

Download my free PHP Handbook!