2

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.

2
  • You probably mean "without manually looping" through the array, don't you? Commented Feb 27, 2012 at 8:05
  • Yes. Without manually looping. Commented Feb 27, 2012 at 8:07

4 Answers 4

13

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.