Is there a PHP equivalent of JavaScript's Array.prototype.some() function
No, there is no short circuiting equivalent in the PHP standard library. There are any number of non-short circuiting solutions, among which array_reduce
would probably fit best:
var_dump(array_reduce([2, 5, 8, 1, 4], function ($isBigger, $num) {
return $isBigger || $num > 10;
}));
It may be worth implementing your own some
/any
/all
functions, or use a library which provides a collection of functional programming primitives like this, e.g. https://github.com/lstrojny/functional-php.
It is not included, but they are easily created. This uses the SRFI-1 names any
and every
but can be renamed some
and all
:
function array_any(array $array, callable $fn) {
foreach ($array as $value) {
if($fn($value)) {
return true;
}
}
return false;
}
function array_every(array $array, callable $fn) {
foreach ($array as $value) {
if(!$fn($value)) {
return false;
}
}
return true;
}