Count duplicates 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
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Count duplicates in an array

Post by GeXus »

I want to count the number of duplicates in an array, and ultimately determine which value is duplicated the most.. so for example

Code: Select all


array(1, 4, 6, 10, 3, 4, 4, 10);

Would return the value 4, since it is duplicated 3 times, which is more than any other items in that array...

Any ideas for the best way to do that?

Thanks!
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

untested

Code: Select all

$sample = array(1, 4, 6, 10, 3, 4, 4, 10); 

$different = count(array_diff(array_unique($sample), $sample));
EDIT | Sorry misread your question, kaszu got it right with array_count_values()
Last edited by John Cartwright on Sat Jan 05, 2008 11:13 am, edited 2 times in total.
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Post by kaszu »

User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post by Oren »

array_unique() may be of interest.

Edit: array_filter() + array_count_values() is what you really need.
Last edited by Oren on Sat Jan 05, 2008 11:19 am, edited 1 time in total.
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Post by GeXus »

Nice, thank you!
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Post by Jonah Bron »

untested

Code: Select all

$array = array(2,4,3,3,7,5,4,2,9,5,5,1,0,0,8);
$nums = array();
$return = 1;
foreach ($array as $part){
    foreach ($nums as $num){if ($num[0]==$part) $num[1]++; break; break;}
    $nums[count($nums)] = array($part, 1);
}
foreach ($nums as $num){
    if ($num[1] > $return) $return = $num[1];
}
Not sure if it really works. :)
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

Untested...

Code: Select all

<?php 

$myArray = array(1, 4, 6, 10, 3, 4, 4, 10);
$resultCount = array();

foreach( $myArray as $tVal ){
	$resultCount[$tVal] ++;
}
arsort($resultCount);

foreach( $resultCount as $myVar => $cnt ){
	echo $myVar . ' repeated ' . $cnt . ' times.';
	break;
}
?>
Post Reply