Core\Arr::firstKey
Gives you the key of the first entry of an array.
First means first in the order the entries were put in, not the smallest key. A map gives you the name the first entry was stored under, and a list gives you "0".
Every key of a Novis array is text, so the key comes back as a string even for a list. You can use it to read the value, to name the entry in a message, or to remember where a walk stopped.
The array is not changed, and nothing inside it moves.
An array with no entries gives you null.
Parameters
$aarray<T>The array to read.
Return value
Returns ?string. The key as a string, or null for the empty array.
Examples
The first key
<?nvs// Shows how to read the key of the first entry of an array.
array<int> $stock = ['apples' => 12, 'pears' => 4];
// First means first in the order the entries were put in. This prints// `apples`.echo Core\Arr::firstKey($stock) ?? 'nothing', "\n";
// The key reads the value. This prints `12`.?string $name = Core\Arr::firstKey($stock);if ($name != null) { echo $stock[$name], "\n";}
// Every key of an array is text, so a list gives you "0". This prints `0`.array<string> $colours = ['red', 'green'];echo Core\Arr::firstKey($colours) ?? 'nothing', "\n";apples120An array with no entries
<?nvs// Shows what `Core\Arr::firstKey` gives you when there is no first entry.
array<int> $stock = [];
// The result is `null`, so this prints `the shelf is empty`.?string $name = Core\Arr::firstKey($stock);if ($name == null) { echo "the shelf is empty\n";}
// One entry is added, and its key is now the first key. This prints `pears`.$stock['pears'] = 4;echo Core\Arr::firstKey($stock) ?? 'nothing', "\n";
// Adding a second entry does not change the first key. This prints `pears`.$stock['apples'] = 12;echo Core\Arr::firstKey($stock) ?? 'nothing', "\n";the shelf is emptypearspearsThe first field to correct
<?nvs// Reports the first field of a form that a person has to correct. The checks// are stored in the order the form shows them, so the first key names the// field the page should jump to.
array<string> $problems = [ 'email' => 'this address is not complete', 'phone' => 'this number is too short',];
?string $field = Core\Arr::firstKey($problems);if ($field == null) { echo "the form is complete\n";} else { echo 'please correct ', $field, ': ', $problems[$field], "\n";}please correct email: this address is not complete