Skip to content

Core\Arr::lastKey

Core\Arr::lastKey(array<T> $a): ?stringCore\Arr::lastKey(
    array<T> $a,
): ?string

Gives you the key of the last entry of an array.

Last means last in the order the entries were put in, not the largest key. A map gives you the name of the entry that was put in last, and a list gives you the last position as text.

Core\Arr::firstKey reads the other end of the same order. Adding a new entry changes the last key and leaves the first key alone.

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 page ended.

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 last key

<?nvs
// Shows how to read the key of the last entry of an array.
array<int> $stock = ['apples' => 12, 'pears' => 4];
// Last means last in the order the entries were put in. This prints `pears`.
echo Core\Arr::lastKey($stock) ?? 'nothing', "\n";
// The key reads the value. This prints `4`.
?string $name = Core\Arr::lastKey($stock);
if ($name != null) {
echo $stock[$name], "\n";
}
// Every key of an array is text, so a list gives you its last position as
// text. This prints `1`.
array<string> $colours = ['red', 'green'];
echo Core\Arr::lastKey($colours) ?? 'nothing', "\n";
Output
pears
4
1

An array with no entries

<?nvs
// Shows what `Core\Arr::lastKey` gives you when there is no last entry.
array<int> $stock = [];
// The result is `null`, so this prints `the shelf is empty`.
?string $name = Core\Arr::lastKey($stock);
if ($name == null) {
echo "the shelf is empty\n";
}
// One entry is added, and its key is now the last key. This prints `pears`.
$stock['pears'] = 4;
echo Core\Arr::lastKey($stock) ?? 'nothing', "\n";
// A second entry goes in behind the first one, so the last key changes. This
// prints `apples`.
$stock['apples'] = 12;
echo Core\Arr::lastKey($stock) ?? 'nothing', "\n";
Output
the shelf is empty
pears
apples

Where a page ended

<?nvs
// Reports where a page of records ended, so the next request can carry on from
// there. The records are stored under their id, in the order the database gave
// them, so the last key is the id to continue after.
array<string> $page = [
'1041' => 'Ada Lovelace',
'1042' => 'Grace Hopper',
'1043' => 'Alan Turing',
];
?string $cursor = Core\Arr::lastKey($page);
if ($cursor == null) {
echo "there are no records left\n";
} else {
echo 'continue after id ', $cursor, ' (', $page[$cursor], ')', "\n";
}
Output
continue after id 1043 (Alan Turing)