Reduce

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

Reduces all input values to a single value with the callback function.

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;

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

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

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

// Output: [28]

Example #2

Using Reduce, Filter, and Map to write to a file and return the path. Reduce opens a file pointer, and Map closes it and returns the path.

Since Reduce always returns a value even with an empty input, we use Filter to prevent an attempt to close a non-existent pointer and returning the path when input is empty.

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

$write = F::Compose([
    F::Reduce(function ($value, $carry) {
        if (!$carry) {
            $path = 'file.txt';
            $carry = [
                'path' => $path,
                'file' => fopen($path, 'w'),
            ];
        }

        fwrite($carry['file'], $value . "\n");

        return $carry;
    }),
    F::Filter(),
    F::Map(function ($carry) {
        fclose($carry['file']);

        return $carry['path'];
    }),
]);

iterator_to_array($write(range(1, 10)));

See Also

  • GroupWhile - Group input values based on a callback function.
  • Scan - Reduce input values, returning the intermediate results.