Core\Arr::first
Gives you the value of the first entry of an array.
First means first in the order the entries were put in, not the smallest key. A list gives you the value at position 0. A map gives you the value that was added first.
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, and then the answer for an empty array and the answer for a first entry holding null are the same. Use Core\Arr::isEmpty when you need to tell those two apart.
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 first value
<?nvs// Shows how to read the first value of an array.
array<string> $queue = ['ada', 'grace', 'lin'];
// First means first in the order the entries were put in. This prints `ada`.echo Core\Arr::first($queue) ?? 'nobody', "\n";
// A map works the same way. The value that was added first is `3`.array<int> $scores = ['ada' => 3, 'lin' => 9];echo Core\Arr::first($scores) ?? 0, "\n";
// The array is not changed, so asking again gives the same value. This// prints `ada`.echo Core\Arr::first($queue) ?? 'nobody', "\n";ada3adaAn array with no entries
<?nvs// Shows what `Core\Arr::first` returns for an array with no entries.
array<string> $waiting = [];
// The result is `null`, so this prints `nobody is waiting`.?string $head = Core\Arr::first($waiting);if ($head == null) { echo "nobody is waiting\n";}
// `??` gives a value to use when the result is `null`. This prints `nobody`.echo Core\Arr::first($waiting) ?? 'nobody', "\n";
// `$holding` has one entry, and its value is `null`. `Core\Arr::first` returns `null` here too.// `Core\Arr::isEmpty` returns `false`, so this prints `one entry, and its value is null`.array<?string> $holding = [null];if (!Core\Arr::isEmpty($holding)) { echo "one entry, and its value is null\n";}nobody is waitingnobodyone entry, and its value is nullThe cheapest offer
<?nvs// Picks the cheapest offer to show on a page. `Core\Arr::sort` puts the// smallest price first, so the first entry is the one to show.
array<int> $prices = [1290, 899, 1450];array<int> $sorted = Core\Arr::sort($prices);
?int $cheapest = Core\Arr::first($sorted);if ($cheapest == null) { echo "no offers today\n";} else { echo 'cheapest: ', $cheapest, " cents\n";}cheapest: 899 cents