Code Modernization: Use array_key_first() to read the first key of an array - #12790
Code Modernization: Use array_key_first() to read the first key of an array#12790Soean wants to merge 1 commit into
Conversation
… array. Reading the first key of an array through `array_keys()` builds a complete array of every key only to keep one entry and throw the rest away. Replace that with `array_key_first()`, which reads the first bucket directly.
|
The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the Core Committers: Use this line as a base for the props when committing in SVN: To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. |
Test using WordPress PlaygroundThe changes in this pull request can previewed and tested using a WordPress Playground instance. WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser. Some things to be aware of
For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation. |
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 65773, which is scoped to the two nested
current( array_keys( $array ) )call sites and is addressed in #12785. This PR 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.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:Both functions return early a few lines above when
$cronsis empty, soisset( $keys[0] )can never be false there. Happy to keep an explicitnull !== $firstguard instead if reviewers prefer the defensive form.Behavior notes
reset()returnsfalsewhilearray_key_first()returnsnull. None of the touched call sites compares the result with===, and most sit behind anempty()guard.$keys[0], the new code is strictly safer:$keys[0]emitted a notice on an empty array,array_key_first()returnsnullquietly.