array_key_last()
Gets the last key of the given 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 last key (index) of the specified array in any case.
This is a polyfill for the function array_key_last(), added in PHP 7.3.
Use array_key_first() when you need to get the first key of the array.
1 time — 0.000003 sec (speed of light) | 50000 times — 0.0001 sec (speed of light)
No Hooks.
Returns
String|Int|null. The last key of the array, if the array is not empty; null otherwise.
Usage
array_key_last( $arr );
- $arr(array) (required)
- The array whose last key needs to be obtained.
Examples
#1 Demo
$key = array_key_last( [ 1, 2 ] ); // 1 $key = array_key_last( [ 'one' => 1, 'two' => 2 ] ); // two
#2 Not affect the internal array pointer
An example of how the internal array pointer is stored.
$arr = [ 'one' => 1, 'two' => 2 ]; reset( $arr ); // switch the internal array pointer echo key( $arr ); // one echo array_key_last( $arr ); // two echo key( $arr ); // one
Changelog
| Since 5.9.0 | Introduced. |
array_key_last() array key last code WP 6.9
function array_key_last( array $array ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.arrayFound
if ( empty( $array ) ) {
return null;
}
end( $array );
return key( $array );
}