Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk mindplay-dk/collections.md
Last active Jan 30, 2019

Embed
What would you like to do?
Linear collection workflow

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:

  1. Avoid overwriting $input (which can be helpful for debugging etc.)
  2. 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.

@alexlvcom

This comment has been minimized.

Copy link

alexlvcom commented Mar 27, 2017

Completely agree

@haampie

This comment has been minimized.

Copy link

haampie commented Apr 7, 2017

In fact I think it wouldn't make sense to have a map & reduce method on the collection itself, because they map to a different type. In Haskell for instance the type of map is (a -> b) -> [a] -> [b]: a collection of a's is mapped to a collection of b's. In PHP you can't specialize a collection easily, but clearly if you'd map an array [User] to an array [string], I would argue a simple free function should do the trick. Same story for reduce.

Methods that return a view of the collection (filter, take) could maybe be part of such a collection class.

@radmen

This comment has been minimized.

Copy link

radmen commented May 29, 2017

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

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.