Arrays\flatMap()

higher-order transformer lazy accepts iterable returns Closure pure
((T → U), int?) → (Iterable → Iterable)
At a glance — Map + flatten in one operation. Null depth means flatten fully.

Creates a Closure that flattens nested arrays up to a given depth and applies a callback to each leaf element along the way.

/**
  * @param callable(mixed):mixed $function Applied to leaf values.
  * @param int|null $n Recursion depth; null flattens fully.
  * @return Closure(iterable<int|string, mixed>):(array<int, mixed>|\Generator<int, mixed>)
  */
Arrays\flatMap(callable $function, ?int $n = null): Closure

Returned Closure

When Arrays\flatMap() 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.

$doubleFlat = Arrays\flatMap(fn($n) => $n * 2);

print_r($doubleFlat([1, [2, [3, 4]], 5]));
// [2, 4, 6, 8, 10]

Curried

This can be called inline using currying.

print_r(Arrays\flatMap('strtoupper', 1)([['a'], ['b', ['c']]]));
// ['A', 'B', ['C']]   // only one level flattened

Details

  • Group: Arrays
  • Subgroup: Array map
  • Since: 0.1.0
  • Source: