Core\Arr::find
Core\Arr::find(array<T> $a, callable(T, string): bool $predicate): ?TCore\Arr::find( array<T> $a, callable(T, string): bool $predicate, ): ?T
Searches an array for the first entry that meets a condition you write, and returns that entry.
You pass the array and a small function. Novis calls that function with one entry at a time, and the function returns true or false. The first time it returns true, Core\Arr::find stops there and the result is that entry. The entries after it are never read. If no entry meets the condition, the result is null.
Your function may take a second parameter. Novis then passes the key of the entry as well, always as a string. In a plain list the key is the position, so it is "0", then "1", then "2".
Good to know: the result is also null when the array stores null as the matching value. Use Core\Arr::findKey when you need to know which entry matched.
Parameters
$aarray<T>The array to search.$predicatecallable(T, string): boolCalled as($value, $key)per entry, and may declare fewer parameters.
Return value
Returns ?T. The matching value, or null when nothing matches. In an array<?T>, this null looks the same as a stored null.
Examples
The first large order
<?nvs// Shows how to pick the first entry of an array that meets a condition.// `Core\Arr::find` returns that entry and reads no entry after it.
array<int> $totals = [12, 40, 130, 95, 210];
// The first total above 100 is 130. This prints 130.?int $large = Core\Arr::find($totals, fn(int $total) => $total > 100);echo $large ?? 0, "\n";
// No total is above 1000, so the result is `null`. This prints "none".?int $huge = Core\Arr::find($totals, fn(int $total) => $total > 1000);if ($huge == null) { echo 'none', "\n";}130noneThe first header a proxy added
<?nvs// Shows the second parameter of the function: the key of the entry. The// program looks for the first header whose name starts with `x-`.
array<string> $headers = [ 'host' => 'shop.example', 'accept' => 'text/html', 'x-forwarded-for' => '203.0.113.7', 'x-request-id' => 'a41f',];
// "x-forwarded-for" is the first name that starts with `x-`. This prints 203.0.113.7.?string $added = Core\Arr::find($headers, fn(string $value, string $key) => Core\Str::startsWith($key, 'x-'));echo $added ?? '', "\n";203.0.113.7The coupon the checkout uses
<?nvs// Shows a check a shop makes at the checkout. The customer typed several// coupon codes, and the shop uses the first one it still accepts.
array<string> $typed = ['WINTER', 'SUMMER24', 'FREESHIP'];array<string> $accepted = ['SUMMER24', 'FREESHIP'];
?string $coupon = Core\Arr::find($typed, fn(string $code) => Core\Arr::contains($accepted, $code));
// "SUMMER24" is the first accepted code. This prints "the coupon SUMMER24 is used".if ($coupon == null) { echo 'no coupon is used', "\n";} else { echo 'the coupon ', $coupon, ' is used', "\n";}the coupon SUMMER24 is used