Core\Arr::last
Gives you the value of the last entry of an array.
Last means last in the order the entries were put in, not the largest key. When you add an entry to the end of a list, that entry is the one you get back.
The array is not changed, and nothing inside it moves, so asking twice gives you the same value both times.
An array with no entries gives you null. An array can also hold null as a value, so a null answer does not on its own say that the array is empty. Core\Arr::isEmpty answers that question.
Parameters
$aarray<T>The array to read.
Return value
Returns ?T. The value, or null for the empty array. In an array<?T>, this null looks the same as a stored null.
Examples
The last value
<?nvs// Shows how to read the last value of an array.
array<string> $queue = ['ada', 'grace', 'lin'];
// Last means last in the order the entries were put in. This prints `lin`.echo Core\Arr::last($queue) ?? 'nobody', "\n";
// The entry you add to the end is the one you get back. This prints `raj`.$queue[] = 'raj';echo Core\Arr::last($queue) ?? 'nobody', "\n";
// A map works the same way. The value that was added last is `9`.array<int> $scores = ['ada' => 3, 'lin' => 9];echo Core\Arr::last($scores) ?? 0, "\n";linraj9An array with no entries
<?nvs// Shows what `Core\Arr::last` gives you when there is no last entry.
array<int> $readings = [];
// The result is `null`, so this prints `no reading yet`.?int $newest = Core\Arr::last($readings);if ($newest == null) { echo "no reading yet\n";}
// `??` names a value to use instead of `null`. This prints `0`.echo Core\Arr::last($readings) ?? 0, "\n";
// The array is not changed by reading it, so the same value comes back every// time. This prints `21 21`.$readings[] = 19;$readings[] = 21;echo Core\Arr::last($readings) ?? 0, ' ', Core\Arr::last($readings) ?? 0, "\n";no reading yet021 21The newest reading
<?nvs// Shows the newest temperature a sensor sent, and how much it changed. A// program keeps the readings in the order they arrived, so the newest one is// the last entry.
array<int> $temperatures = [18, 19, 21, 20];
?int $newest = Core\Arr::last($temperatures);?int $oldest = Core\Arr::first($temperatures);if ($newest == null || $oldest == null) { echo "no readings yet\n";} else { echo 'now: ', $newest, " degrees\n"; echo 'change since the first reading: ', $newest - $oldest, "\n";}now: 20 degreeschange since the first reading: 2