You can have a linear workflow with the array functions.
The following is unreadable:
$output = array_reduce(
array_map(
function($n) { return $n ** 2; }
array_filter($input, function($n) { return $n % 2 == 0; })
),
function($x, $y) { return $x + $y; }
);
To get a more linear workflow, don't reinvent the wheel or introduce new dependencies. Just stick to idiomatic PHP and introduce an intermediary variable:
$output = $input;
$output = array_filter($output, function($n) { return $n % 2 == 0; });
$output = array_map(function($n) { return $n ** 2; }, $output);
$output = array_reduce($output, function($x, $y) { return $x + $y; });
Note that I'm copying $input
to $output
for two reasons:
- Avoid overwriting
$input
(which can be helpful for debugging etc.) - Allows you to freely rearrange all operations on the collection
$output
by simply moving the lines up or down.
This linear workflow also is easier to debug - stepping line-by-line in a debugger will reveal the state of the array after each operation, without having to drill through any call-stacks etc.
Years ago I was frustrated about this inconsistency so I've tried to write my own implementation of array chains. It works (or at least worked) automatically by guessing proper function name and place in list of arguments. https://github.com/radmen/ArrayChain