PHP Functional Programming Common functional methods in PHP



Applying a function to all elements of an array :

array_map('strtoupper', $array);

Be aware that this is the only method of the list where the callback comes first.

Reducing (or folding)

Reducing an array to a single value :

$sum = array_reduce($numbers, function ($carry, $number) {
   return $carry + $number;


Returns only the array items for which the callback returns true :

$onlyEven = array_filter($numbers, function ($number) {
    return ($number % 2) === 0;