Functional Programming in PHP: Part 4

Lochemem Bruno Michael
3 min readDec 13, 2017

--

After elaborately explaining immutability and showing off some helper functions in the bingo-functional library, I will set my sights on construing the array_map, array_reduce, and array_filter functions. In the wise words of New York rappers Jay Z and Swizz Beatz, it is time to move on to the next one.

The next one is quite important. A microcosm of PHP’s rich array function base, array_map(), array_reduce(), and array_filter() are massively significant. The first, array_map() is especially useful for transforming all entries in one or more arrays. A handy tool to have, array_map’s simplicity is matched only by its robustness. Imagine a situation which might require renaming all entries in a multi-dimensional array’s sub-array contexts — the array_map function, in this case, becomes the Prince who was promised.

$characters = [
['id' => 44, 'name' => 'Cersei', 'incest' => true],
['id' => 47, 'name' => 'Jaimie', 'incest' => true ],
['id' => 31, 'name' => 'Daenerys', 'incest' => true],
['id' => 30, 'name' => 'Jon', 'incest' => true],
['id' => 48, 'name' => 'Tyrion', 'incest' => false]
];
$transformed = array_map(
function (array $character) : array {
return [
'age' => $character['id'],
'firstname' => $character['name'],
'hasCommittedIncest' => $character['incest']
];
},
$characters
);
print_r($transformed);//should return something interesting

The snippet above evaluates to a new multidimensional array with renamed array indexes. Also, the array_map function is convenient for mutating many arrays. The caveat is this: the arity of the mutating function is adjusted to reflect the array count. If there are two arrays specified, the arity of the morphism is two and so on.

$houses = ['Targaryen', 'Lannister', 'Stark'];$characters = ['Jon', 'Cersei', 'Daenerys'];$transformed = array_map(
function (string $character, string $house) : array {
return [
'character' => $character,
'house' => $house
];
},
$characters,
$houses
);
//arity of morphism is 2

Next is the array_filter function which, like its name suggests, is a means of removing values from a collection. The quintessential requirements for an array_filter operation are a filter, a function which evaluates to a boolean, and an array. Unlike the array_map function, the array_filter function has an arity of two. The result of a filter operation is not always a value transformation to the same extent as that of an array_map function. The outcome is a result of boolean logic selection.

$incestuous = array_filter(
$characters,
function (array $character) {
return $character['incest'] === true;
}
);
print_r($incestuous);//we all know what this will evaluate to

The array_reduce function, also known as the fold function in Haskell and Scala, last of the trinity of the array functions explained in this article, is one used to create a return value from recursive application of an accumulator value. The accumulator function, that is, the one run recursively, takes two arguments, a specified accumulator, and an array value.

use Chemem\Bingo\Functional\Algorithms\concat;$incest = array_reduce(
$characters,
function (int $acc, array $character) : int {
return $character['incest'] === true ?
$acc + 1 :
$acc;
},
0 //accumulator
);
echo concat(' ', 'Number of characters guilty of incest:', $incest);

The example shown above computes the number of characters who have indulged in incest. Using the fold function certainly lightens the cognitive burden and can be combined with the other functions, array_map, and array_filter to create more complex transformations. It is important to note the significance of setting the right accumulator value as it has a profound effect on fold operations successful or otherwise. Generating an array, which is common to both the map and filter functions is not out of reach with the filter function — a little creativity is all that is required.

In conclusion, a healthy combination of all three functions elucidated in this article is always a good thing. The map, reduce and fold functions all emphasize immutability and function purity — two cornerstone functional programming ideas. Using the trinity of functions described is highly recommended. In the next article in the series, I will discuss exception handling, a polemic topic.

The series — Functional Programming in PHP — is now a book. The volume eponymous with the blog content is currently available on Leanpub.

--

--