vincej Posted May 8, 2012 Share Posted May 8, 2012 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 ! Link to comment https://forums.phpfreaks.com/topic/262274-how-do-i-count-the-positive-values-in-an-array/ Share on other sites More sharing options...
xyph Posted May 9, 2012 Share Posted May 9, 2012 Let's see your foreach. Link to comment https://forums.phpfreaks.com/topic/262274-how-do-i-count-the-positive-values-in-an-array/#findComment-1344110 Share on other sites More sharing options...
Barand Posted May 9, 2012 Share Posted May 9, 2012 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 Link to comment https://forums.phpfreaks.com/topic/262274-how-do-i-count-the-positive-values-in-an-array/#findComment-1344113 Share on other sites More sharing options...
leitning Posted May 9, 2012 Share Posted May 9, 2012 Are you sure the values you're evaluating are integers? Try: $posCount = 0; foreach($array as $value) { if( is_numeric($value) && intval($value) > 0 ) $posCount++; } Link to comment https://forums.phpfreaks.com/topic/262274-how-do-i-count-the-positive-values-in-an-array/#findComment-1344273 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.