In PHP, array_first() returns the first value of an array, no matter what its key is. If the array is empty, it returns null.
You use array_first() to get the first item of a list or of a filtered result without worrying about the keys. After array_filter() the first key is often not 0, so $array[0] fails, but array_first() still works.
Syntax
Call array_first() with the values you need. Start with this line.
PHP
$first = array_first($colors);
Call
What it does
array_first(['red', 'green', 'blue'])
Returns 'red', the first value.
array_first([5 => 'x', 2 => 'y'])
Returns 'x', because it comes first, even though its key is 5.
array_first([])
Returns null for an empty array.
array_first() was added in PHP 8.5. On older versions, use reset($array), which returns false on an empty array, or $array[array_key_first($array)] after you check that the array is not empty. The array is not changed and its internal pointer is not moved.
Library declarations
PHP
array_first(array $array): mixed
Parameters
Parameter
Description
array
Required. The array to read from.
Return Value
Return Value
Description
mixed
The first value of the array, or null when the array is empty.
array_filter() removes the two zeros because they are falsy.
The values 7 and 8 keep their old keys, 2 and 3.
$filtered[0] would not exist here, because there is no key 0.
array_first() returns 7, the first remaining value, whatever its key is.
Frequently Asked Questions
It returns the first value of an array. If the array is empty, it returns null. It does not depend on the array keys.
array_first() was added in PHP 8.5. On older versions use reset(), or read $array[array_key_first($array)] after checking that the array is not empty.
$array[0] reads the item with the key 0, which may not exist after filtering or for associative arrays. array_first() returns the first item in order, whatever its key is.
No. Unlike reset(), array_first() does not change the internal pointer of the array and it does not modify the array.
Use array_key_first(). It returns the first key of the array, or null when the array is empty.