Arrays\filterFirst()

higher-order reducer short-circuit accepts iterable returns Closure pure
(T → bool) → (Iterable → T | null)
At a glance — A higher-order reducer. The returned Closure stops pulling from the source at the first match — safe with infinite Generators. Returns null when nothing matches.

Creates a Closure that returns the first value of an array or iterable that matches the predicate, or null if nothing matches. Short-circuits — the source is consumed only up to (and including) the first match.

/**
  * @param callable(mixed):bool $func Predicate — the first value returning true is returned.
  * @return Closure(iterable<int|string, mixed>):?mixed
  */
Arrays\filterFirst(callable $func): Closure

Returned Closure

When Arrays\filterFirst() 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 scan.
  * @return mixed|null The first matching value, or null if nothing matches.
  */
$function (iterable $source)

Examples

Partial Application

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

// Create a function that returns the first string value found.
$firstString = Arrays\filterFirst('is_string');

// Called as a function.
var_dump($firstString([null, 1, 'b', 2, 'c'])); // 'b'
var_dump($firstString([null, 1, 2]));           // NULL

Curried

This can be called inline using currying.

// Return the first multiple of 15.
var_dump(Arrays\filterFirst(fn($v) => $v % 15 === 0)([1, 2, 3, 15, 30])); // 15

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.

// Drop the Closure straight into another callable if you never intend to reuse it.
$firstNegative = Arrays\filterFirst(fn($n) => $n < 0)([3, 1, 4, -1, 5, -9]);
var_dump($firstNegative); // -1

Works with Iterables & Generators

Accepts a Generator or any Traversable as input.

// Step 1 — a Generator that announces each value as it yields it.
$words = (function () {
    echo "yielded apple\n";    yield 'apple';
    echo "yielded ANT\n";      yield 'ANT';
    echo "yielded banana\n";   yield 'banana';
    echo "yielded BEE\n";      yield 'BEE';
})();

// Step 2 — build a reusable "first lowercase word" finder.
$firstLowercase = Arrays\filterFirst('ctype_lower');

// Step 3 — call it. The Generator is advanced only until the first match is found.
echo $firstLowercase($words);

// Output:
// yielded apple
// apple

// "yielded ANT", "yielded banana", "yielded BEE" never printed — the source was never asked for them.

Details

Arrays Functions

Releated Array filter Functions