Find First or Last Element using array_first or array_last in PHP 8.5

Find First or Last Element using array_first or array_last in PHP 8.5

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_first function returns the first element of the array if it is not empty; otherwise, it returns null.
  • The array_last function returns the last element of the array if it is not empty; otherwise, it returns null.
<?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

Your email address will not be published.