Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Functional Piping in PHP
<?php declare(strict_types = 1);
function pipe(...$args) {
return function ($arg) use ($args) {
$reducer = function ($prev, $fn) {
return $fn($prev);
};
return array_reduce($args, $reducer, $arg);
};
}
function pipeWith($arg, ...$fns) {
return pipe(...$fns)($arg);
}
$odds = function (array $a): array {
return array_filter($a, function ($x) {
return $x % 2 !== 0;
});
};
$double = function (array $a): array
{
return array_map(function ($x) {
return $x * 2;
}, $a);
};
$log = function (array $a): array {
echo implode(', ', $a);
return $a;
};
$data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// These are functionally same and print out '2, 6, 10, 14, 18'
pipe($odds, $double, $log)($data);
pipeWith($data, $odds, $double, $log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.