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.
20/02/2008 at 15:07 Permalink
but yes... map, reduce, walk, all of the 'u' functions (uintersect, etc) let you define a callback, which makes for some nice code.
Reply
20/02/2008 at 15:44 Permalink
print_r(
array_filter(
array(1, 2, 3, 4, 5),
create_function('$x', 'return $x % 2 == 0;')
)
);
Please be aware that array_map() uses a different parameter order than array_filter(), array_reduce() and array_walk().
Reply
20/02/2008 at 16:08 Permalink
In Haskell you need only two short lines (using lambda-functions) for achieving the same result as the given example:
map (\x -> x + 1) [1..5] -- returns [2,3,4,5,6]
foldl1 (\x y -> x + y) [1..5] -- returns 15
This looks native (for Haskell) and I think the use of array_map and array_reduce should look familiar too, just like in the posted article about closures.
Reply
03/03/2008 at 19:56 Permalink
Reply
11/05/2009 at 02:24 Permalink
Reply
24/05/2010 at 02:32 Permalink
http://anton.vedeshin.com/articles/php-mapreduce-similar-implementation-draft
Reply