Reputation: 119
I need to count the times a key/variable is shown inside an array of arrays.
The array looks like this:
Array
{
[3] => Array
{
[type]=>group
[name]=>3st group
[newmsgs]=>3
}
[2] => Array
{
[type]=>group
[name]=>2nd group
}
[1] => Array
{
[type]=>group
[name]=>1st group
[newmsgs]=>1
}
}
I am looking for a function that runs and returns 2 since there are only 2 arrays that have the 'newmsgs' key with value.
I've tried array_count_values()
without success, as well as trying a simple count()
which I knew has a slim chance of working.
Any idea of how to do this?
Upvotes: 2
Views: 38
Reputation: 78994
Extract the column you want and count them:
$count = count(array_column($array, 'newmsgs'));
Upvotes: 1
Reputation: 54841
Mix of array_filter
and sizeof
:
echo sizeof(array_filter($array, function($v) { return !empty($v['newmsgs']); } ));
array_filter
will return array of elements where newmsgs
key is set, and sizeof
will get size of this returned array.
Upvotes: 1