GroupWhile

GroupWhile ( callable $callback )

Groups input values into arrays based on the callback function.

Parameters

callback
bool callback ( mixed $value , array $batch )

If the callback function returns true the current value is added to the current batch. If it returns false it is added to a new batch.

value
The current value.
batch
The current batch of grouped values.

Examples

Example #1

Basic usage example, grouping repeated values.

<?php

use Webbhuset\Pipeline\Constructor as F;

$group = F::GroupWhile(function ($value, $batch) {
    return !$batch                  // Add to batch if empty
        || $value == reset($batch); // Add if value is the same as values in batch
});

$input = [1, 1, 1, 2, 3, 3, 1, 2, 2];

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

// Output: [[1,1,1],[2],[3,3],[1],[2,2]]

Example #2

Group values in groups where the sum of their values is >= 10, and uses Filter to filter any trailing group.

<?php

use Webbhuset\Pipeline\Constructor as F;

$fun = F::Compose([
    F::GroupWhile(function ($value, $batch) {
        return array_sum($batch) < 10;
    }),
    F::Filter(function ($values) {
        return array_sum($values) >= 10;
    })
]);

$input = [1, 2, 3, 4, 5, 6, 7, 8, 9];

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

// Output: [[1,2,3,4],[5,6],[7,8]]

See Also

  • Chunk - Group input values into arrays of a specified size.