Arrays\foldKeys()

higher-order reducer terminal accepts iterable returns Closure pure
((A, int|string, T) → A, A) → (Iterable → A)
At a glance — Like fold but with access to the key at each step. Terminal; streams the source via foreach.

Creates a Closure that reduces an array or iterable left-to-right with the callback receiving each (carry, key, value) triple.

/**
  * @param callable(mixed $carry, int|string $key, mixed $value): mixed $callable
  * @param mixed $initial
  * @return Closure(iterable<int|string, mixed>):mixed
  */
Arrays\foldKeys(callable $callable, $initial = []): Closure

Returned Closure

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

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

Examples

Partial Application

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

$keyValuePairs = Arrays\foldKeys(
  fn($acc, $k, $v) => $acc . "$k=$v; ",
  ''
);

echo $keyValuePairs(['a' => 1, 'b' => 2]); // a=1; b=2;

Details

Arrays Functions

Releated Array fold Functions