array_key_first()
Gets the first key of the passed array. Does not touch the internal pointer of the array.
The function does not care what type of array was passed (indexed or associative), it will return the first key (index) of the specified array in any case.
Polyfill for the function array_key_first(), added in PHP 7.3.
Use array_key_last() when you need to get the last key of the array.
1 time — -0.00003 sec (speed of light) | 50000 times — 0.00 sec (speed of light)
No Hooks.
Returns
String|Int|null. The first key of the array, if the array is not empty; null otherwise.
Usage
array_key_first( $arr );
- $arr(array) (required)
- The array from which to get the first key.
Examples
#1 Demo
$first_key = array_key_first( [ 1, 2 ] ); // 0 $first_key = array_key_first( [ 'one' => 1, 'two' => 2 ] ); // one
#2 An example of how the internal array pointer is stored.
$arr = [ 'one' => 1, 'two' => 2 ]; next( $arr ); // switch the internal array pointer echo key( $arr ); // two echo array_key_first( $arr ); // one echo key( $arr ); // two
Changelog
| Since 5.9.0 | Introduced. |
array_key_first() array key first code WP 6.9
function array_key_first( array $array ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.arrayFound
if ( empty( $array ) ) {
return null;
}
foreach ( $array as $key => $value ) {
return $key;
}
}