Page 1 of 1
How to count specific elements in an array
Posted: Wed Oct 04, 2006 3:29 pm
by spartan7
I have an $array ("john", "pete", "john")
if I use count() I get the result of 3. How do I count just the johns in $array ?
Posted: Wed Oct 04, 2006 3:43 pm
by Luke
I don't know if this is the best way to do it, but it's what popped into my head:
Code: Select all
/**
* Count specific value in an array
* @haystack array
* @needle string
*/
function count_values($haystack, $needle){
$search = array($needle);
return count(array_intersect($haystack, $search));
}
Posted: Wed Oct 04, 2006 3:58 pm
by Christopher
Posted: Wed Oct 04, 2006 4:04 pm
by Luke
alright... with that in mind, this should work...
Code: Select all
/**
* Count specific value in an array
* @haystack array
* @needle string
*/
function count_values($haystack, $needle){
return count(array_keys($haystack, $needle));
}
Posted: Wed Oct 04, 2006 4:50 pm
by volka