Code Modernization: Use array_key_first() to read the first key of an array.
Reading the first key of an array through array_keys() allocates a full array of every key just to keep one entry and discard the rest. array_key_first() reads the first bucket directly.
Follow-up to r63297 / #65773, which is scoped to the two nested current( array_keys( $array ) ) call sites. This commit covers a second shape of the same idea, which that ticket does not include: the key array is assigned to a variable first, then read on the next line.
$keys = array_keys( $wp_registered_sidebars );
$sidebar = reset( $keys );
$sidebar = array_key_first( $wp_registered_sidebars );
13 occurrences across 11 files, in two shapes — reset( $keys ) and $keys[0]. In every case the intermediate variable existed only to carry the key array to the next line and is never read again afterwards.
One change that goes further
In spawn_cron() and _wp_cron() the surrounding check is dropped too:
$keys = array_keys( $crons );
if ( isset( $keys[0] ) && $keys[0] > $gmt_time ) {
if ( array_key_first( $crons ) > $gmt_time ) {
Both functions return early a few lines above when $crons is empty, so isset( $keys[0] ) can never be false there.
Behavior notes
- On an empty array
reset() returns false while array_key_first() returns null. None of the touched call sites compares the result with ===, and most sit behind an empty() guard.
- Where the old code used
$keys[0], the new code is strictly safer: $keys[0] emitted a notice on an empty array, array_key_first() returns null quietly.
Developed in https://github.com/WordPress/wordpress-develop/pull/12790.
Follow-up to r63297.
Props Soean, mukesh27.
See #65773.