dpa89292
dpa89292
2012-02-27 08:03

php检查数组中至少有两个大于0的值

已采纳

I have a PHP array.

Let's say

$array = array(20,1,0, 0, 0,0,8);

I need to check whether at least tow values available greater than 0 in the array. As an example.

$array = array(20,1,0, 0, 0,0,8); 
// True - Above array has at least two values which is > 0

$array = array(0,9,0, 0, 0,0,0); 
// False- Above array doesn't have at least two values which is > 0

I would like to know if there any easy way to get this done without looping through the array.

Thank you.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

4条回答

  • dtlc84438 dtlc84438 9年前

    You can use array_filter() to reduce your array to only non-zero items, then count them:

    $array = array(20, 0, 0, 0, 0, 0, 0);
    $temp = array_filter($array, function($value){
        return $value > 0;
    });
    echo count($temp) >= 2 ? "true" : "false";
    

    Note: For older PHP versions that do not support anonymous functions, you need to create the function separately and pass its name to the array_filter() function as a string.

    点赞 3 评论 复制链接分享
  • douqi5079 douqi5079 9年前

    Without looping? well, you could

    <?php
    $array = array(20,1,0, 0, 0,0,8);
    rsort($array);
    if ($array[0] > 0 && $array[1] > 0) {
      // yippie
    } else {
      // oh no!
    }
    

    but that wouldn't be any better than

    <?php
    $array = array(20,1,0, 0, 0,0,8);
    $greaterThanZero = 0;
    foreach ($array as $v) {
      if ($v > 0) {
        $greaterThanZero++;
        if ($greaterThanZero > 1) {
          $greaterThanZero = true;
          break;
        }
      }
    }
    
    if ($greaterThanZero === true) {
      // yippie
    } else {
      // oh no!
    }
    

    the first solution may be slightly less code, but sort() is more expensive (meaning slower) than the foreach. You see, the foreach can stop once it has reached two positivie hits. sort() will sort the whole array. The answer suggesting array_reduce() will also walk the whole array.

    Design your algorithms in a way that allows for "quick exit". Why continue processing data when you already know the answer? doesn't make sense, only wastes resources.

    点赞 2 评论 复制链接分享
  • douci1851 douci1851 9年前

    Try this method, using array_filter, it basically filters your elements, then you have the count you were looking for

    function positive($var)
    {
        // returns whether the input integer positive
        return($var > 0);
    }
    
    print_r(array_filter($array, "positive"));
    
    点赞 1 评论 复制链接分享
  • douxuan0698 douxuan0698 9年前

    You might want to use array_reduce or something like that

    function reducer($accumulator, $elem){
        if ($elem>0)
            $accumulator++;
        return $accumulator;
    }
    
    $array = array(9,0,0,0);
    $greater_than_zero = array_reduce($array, 'reducer', 0);
    
    点赞 评论 复制链接分享