array_any()WP 6.8.0

Checks whether at least one element of an array satisfies a condition.

Polyfill for array_any(), added in PHP 8.4.

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

1 time — 0.0000122 sec (very fast) | 50000 times — 0.03 sec (speed of light)

No Hooks.

Returns

true|false.

  • true - at least one element passed the check.
  • false - no element passed the check or the array is empty.

Usage

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

Examples

0

#1 Checking for a suitable value

Let’s check whether there is a number greater than 10 in the array.

$numbers = [ 4, 8, 15 ];

$has_large_number = array_any(
	$numbers,
	static function ( $value ) {
		return $value > 10;
	}
);

var_dump( $has_large_number ); // bool(true)

Changelog

Since 6.8.0 Introduced.

array_any() code WP 7.0.4

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

	return false;
}