Friday, June 21, 2013

Building an Array with array_reduce?

Whether it’s twisting a function or taking advantage of side effects and flexible language constructs, it’s no secret I occasionally take joy in writing bastard PHP code (of course I’m a responsible developer and such snippets don’t make it into production). The other day I was in an “evil” mood and did something that might strike most of you as utterly silly; I used array_reduce() to construct an array.

If you’re not familiar with array_reduce(), it’s a function that iteratively reduces a given array to a single value using a callback function. For example, let’s suppose the function array_sum() didn’t exist. We could achieve the desired functionality using array_reduce() like so:

<?php
$nums = [1, 2, 3, 4, 5];
$sum = array_reduce(
    $nums,
    function ($acc, $val) { return $acc + $val; },
    0
);

array_reduce() executes the callback function for each element in the array, passing to it an accumulator and the current array member. The returned value is used as the accumulator value for the next iteration. This is roughly the functional equivalent of this iterative approach:

<?php
$acc = 0;
foreach ($nums as $val) {
    $acc = $acc + $val;
}

All and all this is pretty straightforward. array_reduce() is nothing more than a mechanism that iterates over a list with an available accumulator. But what happens when you realize that nothing mandates the single result value must be a scalar? For functional programmers, this is obvious. For most PHP programmers with a procedural or OO background, this is potentially a jaw-dropping realization.

Suppose we need to build an array using data from the Unicode Consortium’s supplemental windowsZones.xml file. To make things interesting, the keys need to be the values of the mapZones’ type properties, and the members need to be the value in the leading comments. That is, the resulting array must look like this:

Array (
    ["Etc/GMT+12"] => "(UTC-12:00) International Date Line West",
    ["Etc/GMT+11"] => "(UTC-11:00) Coordinated Universal Time-11",
    ["Pacific/Pago_Pago"] => "(UTC-11:00) Coordinated Universal Time-11",
    ["Pacific/Niue"] => "(UTC-11:00) Coordinated Universal Time-11",
    ["Pacific/Midway"] => "(UTC-11:00) Coordinated Universal Time-11",
    ["Pacific/Honolulu"] => "(UTC-10:00) Hawaii",
...

The standard XML-processing strategies become cumbersome because of the requirement pertaining to the comment values, and the next best solution is to script a rudimentary stateful parser. We can iterate each line and extract the textual value if it’s a comment, or extract the attribute value if it’s a mapZone element, and assign to the array when we have both pieces of information available.

<?php
$comValue = '';
$zones = array_reduce(
    file('windowsZones.xml'),
    function ($acc, $line) use (&$comValue) {
        $line = trim($line);
        if (strpos($line, '<!-- (') !== false) {
            $comValue = trim($line, '<!-> ');
        }
        elseif ($pos = strpos($line, 'type="')) {
            $typeValues = substr($line, $pos + 6, -3);
            foreach (explode(' ', $typeValues) as $value) {
                $acc[$value] = $comValue;
            }
        }
        return $acc;
    },
    []
);

Don't bother benchmarking it; this approach is going to be an order of magnitude slower than an iterative foreach loop that builds up the $zones array directly because the PHP run-time just isn't optimized for abuse like this. We’d gain speed with foreach, but then we’d miss an opportunity to explore how things work, blend different concepts together, and just have fun. Ultimately it's little excursions like this that help one grow and become a better programmer.

1 comment:

  1. using array_reduce to build an array is like going on an all butter diet to lose weight

    ReplyDelete