Scan

Scan ( callable $callback [, mixed $initialValue = [] ] )

Reduces all input values to a single value with the callback function, while returning the intermediate result of every iteration.

Parameters

callback
mixed callback ( mixed $value , mixed $carry )
value
The current value that is being reduced.
carry
The return value of previous iteration.
initialValue
The initial value of $carry.

Examples

Example #1

Basic usage example, summing all input values.

<?php
use Webbhuset\Pipeline\Constructor as F;

$scan = F::Scan(function ($value, $carry) {
    return $carry + $value;
}, 0);

$input = [1, 4, 8, 15];

echo json_encode(iterator_to_array($scan($input)));

// Output: [0,1,5,13,28]

Example #2

Building a string, and using Drop to skip the initial value.

<?php
use Webbhuset\Pipeline\Constructor as F;

$function = F::Compose([
    F::Scan(function ($value, $carry) {
        return $carry . $value;
    }, ''),
    F::Drop(1),
]);

$input = ['Hello', ' ', 'world', '!'];

echo json_encode(iterator_to_array($function($input)));

// Output: ["Hello","Hello ","Hello world","Hello world!"]

See Also

  • Reduce - Reduce input values, returning only the final value.