Opened 20 hours ago
Last modified 17 hours ago
#65842 assigned enhancement
Use isset() instead of in_array() over array_keys() for key lookups
| Reported by: | mukesh27 | Owned by: | mukesh27 |
|---|---|---|---|
| Priority: | normal | Milestone: | Future Release |
| Component: | General | Version: | |
| Severity: | normal | Keywords: | has-patch |
| Cc: | Focuses: | performance |
Description
Several places in core test whether an array has a given key by building the full key list and scanning it linearly:
in_array( $key, array_keys( $array ), true )
This allocates a complete copy of every key and walks it — O(n) time and O(n) memory — where isset( $array[ $key ] ) does a single hash lookup in constant time with no allocation.
Change History (3)
This ticket was mentioned in PR #12929 on WordPress/wordpress-develop by @mukesh27.
20 hours ago
#2
- Keywords has-patch added; needs-patch removed
#3
@
17 hours ago
Note that in some cases isset might not give the same result as in_array. For example, if the value of the array element is null, isset will return false.
<?php $array = [ 'foo' => 1, 'bar' => null, 'baz' => 3, ]; $key = 'bar'; if ( in_array( $key, array_keys( $array ), true ) ) { echo 'in_array: true'; } else { echo 'in_array: false'; } echo "\n"; if ( isset( $array[ $key ] ) ) { echo 'isset: true'; } else { echo 'isset: false'; } echo "\n";
Running the above code gives:
in_array: true isset: false
If you are certain that $array will never contain null values, then this is not an issue; but if you are not certain of this, it might be safer to use array_key_exists instead. (See the second example in the documentation for array_key_exists.)
![(please configure the [header_logo] section in trac.ini)](/chrome/site/your_project_logo.png)
Trac ticket: https://core.trac.wordpress.org/ticket/65842
## Use of AI Tools
AI assistance: Yes
Tool(s): Claude
Model(s): Opus 5
Used for: Initial code skeleton and test suggestions; final implementation and tests were reviewed and edited by me.