Expand

Expand ( [ callable $callback ] )

Passes every input value to the callback function, yielding from the resulting Generator.

Parameters

callback
Generator callback ( mixed $value )

Callback function that returns a Generator.

If no callback is supplied, every input value is passed to yield from.

value
The current value.

Examples

Example #1

Basic usage with default callback.

<?php

use Webbhuset\Pipeline\Constructor as F;

$expand = F::Expand();

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

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

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

Example #2

Using Expand to create values of the cartesian product of two arrays.

<?php

use Webbhuset\Pipeline\Constructor as F;

$expand = F::Expand(function ($value) {
    foreach ($value['foos'] as $foo) {
        foreach ($value['bars'] as $bar) {
            yield [
                'foo' => $foo,
                'bar' => $bar,
            ];
        }
    }
});

$input = [
    [
        'foos' => [1, 2, 3],
        'bars' => [4, 5],
    ]
];

echo json_encode(iterator_to_array($expand($input)), JSON_PRETTY_PRINT);

/**
 * Output:
 *  [
 *      {
 *          "foo": 1,
 *          "bar": 4
 *      },
 *      {
 *          "foo": 1,
 *          "bar": 5
 *      },
 *      {
 *          "foo": 2,
 *          "bar": 4
 *      },
 *      {
 *          "foo": 2,
 *          "bar": 5
 *      },
 *      {
 *          "foo": 3,
 *          "bar": 4
 *      },
 *      {
 *          "foo": 3,
 *          "bar": 5
 *      }
 *  ]
 */

See Also

  • Map - Modify every input value with a callback function.