Book Image

Functional PHP

By : Gilles Crettenand
Book Image

Functional PHP

By: Gilles Crettenand

Overview of this book

<p>A functional approach encourages code reuse, greatly simplifies testing, and results in code that is concise and easy to understand. This book will demonstrate how PHP can also be used as a functional language, letting you learn about various function techniques to write maintainable and readable code.</p> <p>After a quick introduction to functional programming, we will dive right in with code examples so you can get the most of what you’ve just learned. We will go further with monads, memoization, and property-based testing. You will learn how to make use of modularity of function while writing functional PHP code.</p> <p>Through the tips and best practices in this book, you’ll be able to do more with less code and reduce bugs in your applications. Not only will you be able to boost your performance, but you will also find out how to eliminate common loop problems. By the end of the book, you will know a wide variety of new techniques that you can use on any new or legacy codebase.</p>
Table of Contents (19 chapters)
Functional PHP
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

The fold or reduce function


Folding refers to a process where you reduce a collection to a return value using a combining function. Depending on the language, this operation can have multiple names like fold, reduce, accumulate, aggregate, or compress. As with other functions related to arrays, the PHP version is the array_reduce function.

You may be familiar with the array_sum function, which calculates the sum of all the values in an array. This is, in fact, a fold and can be easily written using the array_reduce function:

<?php

function sum(int $carry, int $i): int
{
    return $carry + $i;
}

$summed = array_reduce([1, 2, 3, 4], 'sum', 0);
/* $summed contains 10 */

Like the array_filter method, the collection comes first; you then pass a callback and finally an optional initial value. In our case, we were forced to pass the initial value 0 because the default null is an invalid type for our function signature of int type.

The callback function has two parameters. The first one is the...