Arrays\map()

higher-order transformer lazy accepts iterable returns Closure pure
(T → U) → (Iterable → Iterable)
At a glance — The canonical map. Lazy — Generator in, Generator out, keys preserved.

Creates a Closure that applies a callback to every element of an array or iterable, yielding a new collection of transformed values. Keys are preserved.

/**
  * @param callable(mixed):mixed $func
  * @return Closure(iterable<int|string, mixed>):(array<int|string, mixed>|\Generator<int|string, mixed>)
  */
Arrays\map(callable $func): Closure

Returned Closure

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

/**
  * @param iterable<int|string, mixed> $source
  * @return array<int|string, mixed>|\Generator<int|string, 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.

$double = Arrays\map(fn($n) => $n * 2);

print_r($double([1, 2, 3])); // [2, 4, 6]

Curried

This can be called inline using currying.

print_r(Arrays\map('strtoupper')(['a', 'b'])); // ['A', 'B']

Inlined with Higher Order Function

If you are not planning on reusing the Closure created, you can just call it inline with a higher order function as its callable.

$upper = array_map('strtoupper', ['a', 'b']); // vanilla PHP

Details

  • Group: Arrays
  • Subgroup: Array map
  • Core Functions: array_map()
  • Since: 0.1.0
  • Source: