array_find_key()WP 6.8.0

Finds the key of the first array element that satisfies a condition.

Polyfill for array_find_key(), added in PHP 8.4.

The callback receives the value and key of each element. Searching stops after the first true result.

No Hooks.

Returns

Int|String|null.

  • int - the numeric key of the matching element.
  • string - the string key of the matching element.
  • null - no matching element was found or the array is empty.

Usage

array_find_key( $array, $callback );
$array(array) (required)
Array to search.
$callback(callable) (required)
A callback with the form callback( $value, $key ): bool.

Examples

0

#1 Search for a key by value

We’ll find the key of the first value greater than 10.

$numbers = [
	'first'  => 4,
	'second' => 15,
	'third'  => 23,
];

$key = array_find_key(
	$numbers,
	static function ( $value ) {
		return $value > 10;
	}
);

var_dump( $key ); // string(6) "second"

Changelog

Since 6.8.0 Introduced.

array_find_key() code WP 7.0.4

function array_find_key( array $array, callable $callback ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.arrayFound
	foreach ( $array as $key => $value ) {
		if ( $callback( $value, $key ) ) {
			return $key;
		}
	}

	return null;
}