duanrong5167 2013-03-22 20:55
浏览 9

我怎么能用Ruby中的“任何?”做同样的事情

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?

  • 写回答

2条回答 默认 最新

  • douxi3554 2013-03-22 21:00
    关注

    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;
    }
    
    评论

报告相同问题?