Rory Rory - 2 months ago 14
Javascript Question

Is there a PHP equivalent of JavaScript's Array.prototype.some() function

In JavaScript, we can do:

function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

Is there a PHP equivalent of the some() function?

Answer

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.