I do not do much PHP development except for some small WordPress things. I often need to get the first or last element from an array that also may be empty. To my knowledge there are two approaches that are safe.
1: $first = $array[0] ?? null; $last = $array[count( $array ) - 1] ?? null;
2: $first = reset( $array ); $last = end( $array );
Are there others? Is there a community consensus? WordPress specific consensus?
Community addition: Since this answer was written, new functions have been added to PHP, suggested in respective answers: array_key_first() (PHP 7.3+) and, finally, array_first() (PHP 8.5+).
Original answer, but costly (O(n)):
array_shift(array_values($array));
In O(1):
array_pop(array_reverse($array));
Other use cases, etc...
If modifying (in the sense of resetting array pointers) of $array is not a problem, you might use:
reset($array);
This should be theoretically more efficient, if a array "copy" is needed:
array_shift(array_slice($array, 0, 1));
With PHP 5.4+ (but might cause an index error if empty):
array_values($array)[0];
As Mike pointed out (the easiest possible way):
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo reset($arr); // Echoes "apple"
If you want to get the key: (execute it after reset)
echo key($arr); // Echoes "4"
From PHP's documentation:
mixed reset ( array | object &$array );
Description:
reset() rewinds array's internal pointer to the first element and returns the value of the first array element, or FALSE if the array is empty.
For Beginners: How to get the first element of an array
How to get first value from array? - PHP - SitePoint Forums | Web Development & Design Community
How to get the first element in the Associative array.
php - First element of array by condition - Stack Overflow
Videos
There's no need to use all above mentioned functions like array_filter. Because array_filter filters array. And filtering is not the same as find first value. So, just do this:
foreach ($array as $key => $value) {
if (meetsCondition($value)) {
$result = $value;
break;
// or: return $value; if in function
}
}
array_filter will filter whole array. So if your required value is first, and array has 100 or more elements, array_filter will still check all these elements. So, do you really need 100 iterations instead of 1? The answer is clear - no.
The shortest I could find is using current:
current(array_filter($input, function($e) {...}));
current essentially gets the first element, or returns false if its empty.
If the code is being repeated often, it is probably best to extract it to its own function.