The Map, Filter, and Fold Functions
Learn about the map, filter, and fold functions in the bingo-functional library.
Background
Lists are universal in programming. Their importance lies in storing multiple values. The basic list type in PHP is the associative array (or hash table). There exist numerous list types in PHP other than the associative array. The SPL fixed array, object storage, doubly linked lists, heaps, and stacks form one list genealogy. The immutable lists and collections form another list grouping.
Regardless of list type, the need to manipulate data stored in lists is a fundamental requirement. While it is possible to manipulate list data using iterative control structures (for
, while
, foreach
loops and the like), the map
, filter
, and fold
patterns suffice as more stylistically appropriate artifacts for modifying lists. These three higher-order functions are similar in the sense that they create new list data via function application in one go, but differ from each other algorithmically otherwise.
The map
function
The map
function applies a function to each value in a list. The PHP userland has an array_map
function, which is convenient for this purpose. Multiple arrays can be parsed by the array_map
function.
Below, is a mapping of the factorial
function on each value in a list of numbers.
Get hands-on with 1400+ tech skills courses.