Arrays\take()

transformer short-circuit accepts iterable returns Closure pure throws
int → (Iterable → Iterable)
At a glance — Bind a cap; the returned Closure pulls up to that many values and stops. Throws on negative counts.

Creates a Closure that takes the first N elements of an array or iterable. For Generators, only those N values are pulled — the source is not advanced past them.

/**
  * @param int $count
  * @return Closure(iterable<int|string, mixed>):(array<int|string, mixed>|\Generator<int|string, mixed>)
  * @throws \InvalidArgumentException if count is negative.
  */
Arrays\take(int $count = 1): Closure

Returned Closure

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

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

Works with Iterables & Generators

Accepts a Generator or any Traversable as input.

$naturals = (function () { $i = 1; while (true) yield $i++; })();

foreach (Arrays\take(5)($naturals) as $n) echo $n; // 12345
// Rest of the Generator is never pulled — infinite source is safe here.

Details

Arrays Functions

Releated Array take Functions