2

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?

2 Answers 2

1

Extract the column you want and count them:

$count = count(array_column($array, 'newmsgs'));
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you AbraCadaver, this works perfectly too! just had to test and see if this work as it seems a little simpler than u_mulder and it works as well. Thanks!
I'm not AbraCadaver_da_boss? :-(
I would say AbraCadaver_da_king :D
1

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.

1 Comment

u_mulder, you should update your name to u_mulder_da_boss. This worked perfectly and is elegant! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.