JavaScript has the concept of array checker functions some
and every
, basically checking if a condition applies to either at least one or all elements of an array.
function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
Is there an equivalent way for php?
Now you can use them like you'd expect
echo (int) array_any(function($x) { return $x > 5; }, [1,2,3]); // 0
echo (int) array_any(function($x) { return $x > 5; }, [1,9,3]); // 1
echo (int) array_all(function($x) { return $x > 5; }, [5,6,7]); // 0
echo (int) array_all(function($x) { return $x > 5; }, [6,7,8]); // 1
@ggorlen suggests switching on truthy values provided by the callback. All values in PHP are considered true except the following:
type | value |
---|---|
boolean | false |
int | 0 |
float | 0.0 and -0.0 |
string | "" |
array | [], empty array |
null | null |
object | overloaded objects |
Watch out for NAN
, it is considered true
.
function array_any(callable $f, array $xs) {
foreach ($xs as $x)
if (call_user_func($f, $x) == true) // truthy
return true;
return false;
}
function array_all(callable $f, array $xs) {
foreach ($xs as $x)
if (call_user_func($f, $x) == false) // truthy
return false;
return true;
}
Remember: programming isn't magic. Different languages offer different native features/functionality, but that doesn't always mean you're stuck when you find your language is "missing" something.
Taking on the challenge of implementing these things on your own can be fun and rewarding.
function array_any(callable $f, array $xs) {
foreach ($xs as $x)
if (call_user_func($f, $x) === true)
return true;
return false;
}
function array_all(callable $f, array $xs) {
foreach ($xs as $x)
if (call_user_func($f, $x) === false)
return false;
return true;
}