Core\Arr::findKey
Searches an array for the first entry that meets a condition you write, and returns the key of 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::findKey stops there and the result is the key of that entry. The entries after it are never read. If no entry meets the condition, the result is null.
The key is always a string, whatever you wrote it as. In a plain list the key is the position, so it is "0", then "1", then "2". Your function may take the key as a second parameter as well.
Good to know: use Core\Arr::find when you want the entry itself instead of its key.
Parameters
$aarray<T>The array to search.$predicatecallable(T, string): boolCalled as($value, $key)per entry, and may declare fewer parameters.
Return value
Returns ?string. The key as a string, whatever it was written as; null when nothing matches.
Examples
The position of the first warm day
<?nvs// Shows how to get the position of the first entry that meets a condition.// In a list the key is the position, and it is always a string.
array<int> $temperatures = [18, 21, 34, 22];
// 34 is the first value above 30, and it sits at position 2. This prints 2.?string $warm = Core\Arr::findKey($temperatures, fn(int $degrees) => $degrees > 30);echo $warm ?? 'none', "\n";
// No value is below zero, so the result is `null`. This prints "none".?string $frozen = Core\Arr::findKey($temperatures, fn(int $degrees) => $degrees < 0);echo $frozen ?? 'none', "\n";2noneThe name of the first full shelf
<?nvs// Shows a search over an array that uses names as keys. The result is the// name of the entry, not the value stored under it.
array<int> $shelves = [ 'fiction' => 12, 'cooking' => 40, 'travel' => 8,];
// "cooking" is the first shelf holding more than 20 books. This prints cooking.?string $full = Core\Arr::findKey($shelves, fn(int $books) => $books > 20);echo $full ?? 'none', "\n";cookingThe first empty form field
<?nvs// Shows a check a program makes after a form is sent. It names the first// field the visitor left empty.
array<string> $form = [ 'name' => 'Ada', 'email' => '', 'message' => 'Hello',];
?string $missing = Core\Arr::findKey($form, fn(string $value) => Core\Str::length($value) == 0);
// The field "email" is empty. This prints "please fill in email".if ($missing == null) { echo 'the form is complete', "\n";} else { echo 'please fill in ', $missing, "\n";}please fill in email