Since PHP 8.5, we can use the array_first and array_last functions to retrieve the first and last elements of an array. These functions serve as counterparts to array_key_first and array_key_last, providing a convenient way to access elements directly.
- The
array_firstfunction returns the first element of the array if it is not empty; otherwise, it returnsnull. - The
array_lastfunction returns the last element of the array if it is not empty; otherwise, it returnsnull.
<?php
$array = [10, 20, 30, 40, 50];
echo array_first($array); // 10
echo array_last($array); // 50
If the array is empty, both functions return null, making them convenient to use with the ?? operator.
<?php
echo array_first([]) ?? -1; // -1
echo array_last([]) ?? -1; // -1
Leave a Comment
Cancel reply