30 seconds of PHP

  Back to Home

compose

functionintermediate

Return a new function that composes multiple functions into a single callable.

Use array_reduce() to perform right-to-left function composition.

function compose(...$functions)
{
  return array_reduce(
    $functions,
    function ($carry, $function) {
      return function ($x) use ($carry, $function) {
        return $function($carry($x));
      };
    },
    function ($x) {
      return $x;
    }
  );
}