There is none (as of PHP 7.3).
You could use a clearer, but less efficient syntax using array_reduce()
:
function satisfies(array $objectArray, $callback) {
return array_reduce(
$objectArray,
function($found, $item) use ($callback) {
return $found || call_user_func($callback, $item);
},
false
);
}
$has = satisfies($array, function($obj) { return $obj->name === 'foo'; });
The function will call iteratively the callback until it returns true
, then it will continue walking the whole array (albeit reasonably quickly). If no element in the array returns a truthy value, the function returns false
.
Issuing a call and passing an object at each iteration, the function is slower than a plain foreach
.
And, as @Jeto very correctly pointed out, I have over-engineered it. Could have written
function satisfies(array $objectArray, $callback, $ifFound = true, $ifNotFound = false) {
foreach ($objectArray as $obj) {
if (call_user_func($callback, $obj)) {
return $ifFound;
}
}
return $ifNotFound;
}