array_find_key()WP 6.8.0

Polyfill for array_find_key() added in PHP 8.4.

Searches an array for the first key that passes a given callback.

No Hooks.

Return

Int|String|null. The first key in the array that passes the $callback, otherwise null.

Usage

array_find_key( $array, $callback );
$array(array) (required)
The array to search.
$callback(callable) (required)
The callback to run for each element.

Changelog

Since 6.8.0 Introduced.

array_find_key() code WP 6.8

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;
}