Jump to content

How do I count the positive values in an array ?


vincej

Recommended Posts

HI - I have tried COUNT and array_count _values but they don't do what I want.

 

I have an array of 'quantities' relating to orders.

 

I want to count how many key=>value pairs have a positive value that is to say Not 0 or null or "".

 

So for example array ( shoes=>5, coats=> 3, ties=>0)

 

The answer I seek in this case would be 2 as ties is zero.

 

I don't want to know what the aggregate of the values are or other such info.

 

I have tried looping through with a foreach loop testing for $value > 0  and I failed miserably

 

Any ideas ?

 

Many Thanks !

 

 

try

function posval($v) {
    return $v >= 1;
}

$a = array ( 
    'shoes' => 5, 
    'coats' => 3, 
    'ties'  =>  0, 
    'jackets' => '', 
    'socks' => null
    );

$posvals =  count(array_filter($a, 'posval')) ;     // 2

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.