array_find()WP 6.8.0

Finds the first array value that satisfies a condition.

Polyfill for array_find(), 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

Mixed|null.

  • mixed - the first value that passes the check.
  • null - no matching value was found, the array is empty, or the found value is null.

Usage

array_find( $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 the first suitable value

We’ll find the first number greater than 10.

$numbers = [ 4, 15, 8, 23 ];

$number = array_find(
	$numbers,
	static function ( $value ) {
		return $value > 10;
	}
);

var_dump( $number ); // int(15)

Changelog

Since 6.8.0 Introduced.

array_find() code WP 7.0.4

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

	return null;
}