nikic/iter

Array keys in callable for 'reduce' function

alxsad opened this issue · 5 comments

I think will be better if developers will be able to get a key.

Example:

use iter as f;

f\reduce(function ($acc, $value, $key) {
    $acc .= sprintf("%s: %s\n", $key, $value);
    return $acc;
}, $response->headers->all(), '');

Or I can do it otherwise?

3onyc commented

Having $key as the last parameter would be similar to array_walk, how to handle $startValue though?

$key as the last parameter in callable.

function reduce(callable $function, $iterable, $startValue = null) {
    _assertIterable($iterable, 'Second argument');
    $acc = $startValue;
    foreach ($iterable as $key => $value) {
        $acc = $function($acc, $value, $key);
    }
    return $acc;
}
3onyc commented

Wasn't fully awake yet, problem I raised doesn't exist.

@alxsad You could make a pull request adding the key parameter + tests.

nikic commented

#28 is merged.