array_all()WP 6.8.0

Checks whether all elements of an array satisfy the specified condition.

Polyfill of the array_all() function added in PHP 8.4.

Passes the value and key of each array element to the callback function. The check stops after the first element for which the callback function returned false.

No Hooks.

Returns

true|false.

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

Usage

array_all( $array, $callback ): bool;
$array(array) (required)
The array to be checked.
$callback(callable) (required)
A validation function of the form callback( $value, $key ): bool, where $value is the element value, $key is its key.

Examples

0

#1 Checking all array elements

Let's check that all values are positive numbers.

$numbers = [ 10, 25, 7 ];

$is_positive = array_all(
	$numbers,
	static function ( $value ) {
		return $value > 0;
	}
);

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

Changelog

Since 6.8.0 Introduced.

array_all() code WP 7.0.4

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

	return true;
}