Yohio Yohio - 4 months ago 18
PHP Question

Need to find array of array with specific key

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?

Thanks!

Answer

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.

Comments