How to count specific elements in an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
spartan7
Forum Commoner
Posts: 29
Joined: Sun Jun 19, 2005 12:09 am

How to count specific elements in an array

Post 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 ?
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post 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));
}
Last edited by Luke on Wed Oct 04, 2006 4:03 pm, edited 1 time in total.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

(#10850)
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post 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));
}
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Post Reply