Arrays\flattenByN()

transformer lazy accepts iterable returns Closure pure
int? → (Iterable → Iterable)
At a glance — Depth-limited flatten. Pass null (or no argument) to flatten fully. Lazy on Generator input.

Creates a Closure that flattens nested arrays up to a specified depth. Empty nested arrays are dropped.

/**
  * @param int|null $n Depth to flatten. Null = fully.
  * @return Closure(iterable<int|string, mixed>):(array<int, mixed>|\Generator<int, mixed>)
  */
Arrays\flattenByN(?int $n = null): Closure

Returned Closure

When Arrays\flattenByN() is called, it returns the following Closure which can be used like a regular function.

/**
  * @param iterable<int|string, mixed> $source
  * @return array<int, mixed>|\Generator<int, mixed>
  */
$function (iterable $source): array|\Generator

Examples

Partial Application

This can be used to create a simple closure which can be used as a regular function.

$flatOne = Arrays\flattenByN(1);

print_r($flatOne([1, [2, [3, 4]], 5]));
// [1, 2, [3, 4], 5]

$flatAll = Arrays\flattenByN();
print_r($flatAll([1, [2, [3, 4]], 5]));
// [1, 2, 3, 4, 5]

Curried

This can be called inline using currying.

print_r(Arrays\flattenByN(2)([[[1]], [[2], [3]]]));
// [1, [2], [3]]    // wait — 2 levels deep

Details

Arrays Functions

Releated Array manipulation Functions