Skip to main content

Posts

Showing posts from June, 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. The other day I was in an evil mood and 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, 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 + $…