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): ClosureWhen 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|\GeneratorThis 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]
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.