Arrays\filterLast()

higher-order reducer terminal accepts iterable returns Closure pure
(T → bool) → (Iterable → T | null)
At a glance — A reducer that returns the last match, not the first. Terminal — must consume the whole source to know which match is last. Do not use with infinite Generators.

Create a function which filters an array but returns only the last value (not as an array)

/**
 * Creates a Closure for running array filter and getting the last value.
 *
 * @param callable $func
 * @return Closure(array<int|string, mixed>):?mixed
 */
Arrays\filterLast(callable $callback): Closure

Returned Closure

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

/**
 * @param array<int|string, mixed> $array The array to filter
 * @return mixed|null The last element from the filtered array or null if filter returns empty
 */
$function (array $data): mixed

Examples

Partial Application

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

// Create a function that will return the last value that is a string.
$filter = Arrays\filterLast('is_string');
// Called as a function.
var_dump($filter([null, 1, 'b', 2, 'c'])); // 'c'

Curried

This can be called inline using currying.

// Return the last value which is a multiple of 3 and 5.
var_dump(Arrays\filterLast(fn($v) => $v % 3 === 0 && $v % 5 === 0)  
([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 30]));  // 30

Details

Arrays Functions

Releated Array filter Functions