Creates a Closure which filters an array or iterable using the defined predicate. Keys are preserved.
/**
* @param callable(mixed):bool $callable Predicate — return true to keep the value.
* @return Closure(iterable<int|string, mixed>):(array<int|string, mixed>|\Generator<int|string, mixed>)
*/
Arrays\filter(callable $callable): ClosureWhen Arrays\filter() is called, it returns the following Closure which can be used like a regular function.
/**
* @param iterable<int|string, mixed> $source Array or iterable to filter.
* @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.
// Create a function that filters out all values that are not strings.
$onlyStrings = Arrays\filter('is_string');
// Called as a function — array in, array out.
var_dump($onlyStrings(['a', 1, 'b', 2])); // ['a', 'b']This can be called inline using currying.
// Filter an array for all even numbers.
var_dump(Arrays\filter(fn($v) => $v % 2 === 0)([1, 2, 3, 4, 5])); // [2, 4]If you are not planning on reusing the Closure created, you can just call it inline with a higher order function as its callable.
// Pass the Closure straight into another higher order function.
$positives = array_filter([-2, -1, 0, 1, 2], Arrays\filter(fn($v) => $v > 0));
Accepts a Generator or any Traversable as input.
// Step 1 — define a Generator source that yields one word at a time.
$words = (function () {
yield 'apple';
yield 'ANT';
yield 'banana';
yield 'BEE';
})();
// Step 2 — build a reusable filter from the predicate.
$lowercaseOnlyFilter = Arrays\filter('ctype_lower');
// Step 3 — apply the filter to the Generator. Nothing runs yet; this returns a new Generator.
$lowercaseOnly = $lowercaseOnlyFilter($words);
// Step 4 — consume with foreach. Each value is pulled from the source on demand and the predicate is checked only when needed.
foreach ($lowercaseOnly as $word) {
echo $word . PHP_EOL;
}
// apple
// banana