PHP Functional Programming Common functional methods in PHP

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Mapping

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;
});

Filtering

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

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


Got any PHP Question?