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 ?
How to count specific elements in an array
Moderator: General Moderators
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));
}
Last edited by Luke on Wed Oct 04, 2006 4:03 pm, edited 1 time in total.
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
I looked:
first here: http://www.php.net/manual/en/ref.array.php
then here: http://www.php.net/manual/en/function.array-search.php
then here: http://www.php.net/manual/en/function.array-keys.php
first here: http://www.php.net/manual/en/ref.array.php
then here: http://www.php.net/manual/en/function.array-search.php
then here: http://www.php.net/manual/en/function.array-keys.php
(#10850)
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));
}