简体   繁体   中英

php check at least two values greater than 0 in array

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.

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.

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"));

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM