Map and Reduce in PHP
Just like Python, PHP is not a full-fledged functional language, but it supports some very useful functional idioms such as Map, Filter, and Reduce. A blog posting by Scott Moonen on Functional Python prompted me to write this posting on PHP's array_map(), array_filter(), and array_reduce() functions that apply callbacks to arrays.
Map
The array_map() function applies the callback to the elements of the given array(s) and returns the result. This example adds 1 to each element of the array:
<?php
print_r(
array_map(
create_function('$x', 'return $x + 1;'),
array(1, 2, 3, 4, 5)
)
);
?>Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 )
Filter
The array_filter() function takes an array and a callback that returns a boolean value as its input and returns a new array containing only the elements for which the callback returns true.
<?php
print_r(
array_filter(
array(1, 2, 3, 4, 5),
create_function('$x', 'return $x % 2 == 0;')
)
);
?>Array ( [1] => 2 [3] => 4 )
Reduce
Provided with an array and a callback, array_reduce() reduces that array by applying the callback to pairs of elements in the array. An example is the best way to understand this. Let's say we want to find the sum of all the elements in an array:
<?php
print array_reduce(
array(1, 2, 3, 4, 5),
create_function('$x, $y', 'return $x + $y;')
);
?>15
The examples above use PHP's create_function() function to create anonymous functions for the callbacks. True, this looks ugly. But maybe one day we get closures in PHP.
By the way: Google's MapReduce programming model (which is implemented by Apache Hadoop, for instance) builds upon the combination of
Update: Added the section on array_filter() in response to a comment by René Leonhardt.
