Page 1 of 1

Count duplicates in an array

Posted: Sat Jan 05, 2008 11:03 am
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!

Posted: Sat Jan 05, 2008 11:11 am
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()

Posted: Sat Jan 05, 2008 11:11 am
by kaszu

Posted: Sat Jan 05, 2008 11:13 am
by Oren
array_unique() may be of interest.

Edit: array_filter() + array_count_values() is what you really need.

Posted: Sat Jan 05, 2008 11:16 am
by GeXus
Nice, thank you!

Posted: Sat Jan 05, 2008 11:25 am
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. :)

Posted: Sat Jan 05, 2008 2:52 pm
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;
}
?>