Map and Reduce in PHP

Sebastian Bergmann » 20 February 2008 » in PHP » 6 Comments

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 map and reduce in a parallel computing environment.

Update: Added the section on array_filter() in response to a comment by René Leonhardt.

Defined tags for this entry: , , , ,

Trackback specific URI for this entry

6 Comments to "Map and Reduce in PHP"

Display comments as (Linear | Threaded)
  1. OnyxRaven
    20/02/2008 at 15:07 Permalink
    create_function() tends to do wierd things - until we get true 'compiled' anonymous functions or closures, I'd recommend using a real defined function in places where any speed matters. I get the feeling from usage that create function is doing an eval() at worst, and that doesnt get picked up by caching mechanisms (apc, eaccelerator, etc)

    but yes... map, reduce, walk, all of the 'u' functions (uintersect, etc) let you define a callback, which makes for some nice code.

    Reply

  2. René Leonhardt
    20/02/2008 at 15:44 Permalink
    PHP knows another functional idiom: filter.

    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

  3. Andre Moelle
    20/02/2008 at 16:08 Permalink
    Indeed, create_function in combination with array_map and array_reduce is very useful for some problems, but in my opinion it is rather a hack than a solution, since declaring larger functions looks very like eval. ;-)

    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

  4. saem
    03/03/2008 at 19:56 Permalink
    Just a note, create_function can be rather dangerous. It creates an anonymous function within the global scope, and so you can chew through memory if you put it inside a loop.

    Reply

  5. Anton Vedeshin
    11/05/2009 at 02:24 Permalink
    trying to make similar to Map / Reduce implementation on PHP http://www.sourceforge.net/phpmapreduce

    Reply

  6. Anton Vedeshin
    24/05/2010 at 02:32 Permalink
    Looking for contributors on PHP Map/Reduce project
    http://anton.vedeshin.com/articles/php-mapreduce-similar-implementation-draft

    Reply

1 Trackback to "Map and Reduce in PHP"

  1. PHPDeveloper.org 20/02/2008 at 15:20
    In this new blog entry, Sebastian Bergmann talks about two bits ...

Add Comment


To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

Submitted comments will be subject to moderation before being displayed.