skolind
skolind

Reputation: 1754

Count in array where value is 0

I'm really stuck here. Im having an array looking like this below. And now I would like to count postStatus where postStatus = 0, for all of the arrays.

So in this case there would be 2. But how do I do this?

Array
(
[1] => Array
    (
        [postId] => 1
        [postHeader] => Post-besked #1
        [postContent] => Post content #1 
        [postDate] => 2011-12-27 17:33:11
        [postStatus] => 0
    )

[2] => Array
    (
        [postId] => 2
        [postHeader] => Post-besked #2 
        [postContent] => POst content #2
        [postDate] => 2011-12-27 17:33:36
        [postStatus] => 0
    )
)

Upvotes: 0

Views: 627

Answers (3)

Jeune
Jeune

Reputation: 3538

How about this? Compact and concise :)

$postStatusCount = array_sum(array_map(
    function($e) { 
            return array_key_exists('postStatus', $e)  && $e['postStatus'] == 0 ? 1 :  0; 
    } , $arr)
);

Upvotes: 1

Mathieu Dumoulin
Mathieu Dumoulin

Reputation: 12244

Just loop the outer array, check if there is a postStatus, increment a value to keep that count and you're done...

$postStatus = 0;
foreach($myarray as $myarraycontent){
    if(isset($myarraycontent['postStatus']) && $myarraycontent['postStatus'] == 0){
        $postStatus++;
    }
}
echo $postStatus;

EDIT:

I forgot to mention that isset() can be used but a better pratice is to use array_key_exists because if $myarraycontent['postStatus'] is NULL, it will return false. Thats the way isset() works...

Upvotes: 5

KingCrunch
KingCrunch

Reputation: 131891

$count = count(
  array_filter(
    $array, 
    function ($item) {
        return isset($item['postStatus']);
    }
  )
);

Upvotes: 3

Related Questions