In Ruby, any?
takes a block and check if given collection has a value that fulfills the block like this:
[1, 2, 3].any? {|v| v > 2} # true
Is there any way to do this in PHP? My current idea is to use array_reduce()
:
array_reduce(array(1, 2, 3), function($acc, $val) {
return $acc || ($val > 2);
}, false);
But it will itereate all elements in the array, so I guess it's not as good as "any?" in Ruby. How can I return the boolean value as soon as expected value is found in PHP?
You're too keen about functional programming. PHP is not a functional language; at least that is not its main job.
$array = array(1,2,3);
foreach ($array as $value) {
if ($value > 2) return $value;
}
function any(array $array, callable $test) {
foreach ($array as $value) {
if ($test($value)) {
return true;
}
}
return false;
}
You could use a simple array_filter
instead, but it will iterate the whole array every time:
if (array_filter($array, function ($v) { return $v > 2; })) ...