Page 1 of 1

counting duplicate elements in array

Posted: Sat Aug 03, 2002 5:17 am
by sebamed
I thought something like this, on the first run it didn't work, as I wanted. So if anyone could the check even if the idea is right I’d appreciate it

Code: Select all

while(list($key, $val) =each($array) {
$count = $count_elementsї$val]++;
}

Posted: Sat Aug 03, 2002 8:23 am
by hob_goblin

Code: Select all

$array = array("foo", "foo", "bar");
$count = 0;
for($i = 0; $i < count($array); $i++)&#123;
$tmp = $array&#1111;$i];
unset($array&#1111;$i]);
if(in_array($tmp, $array))&#123;
$count++;
&#125;
$array&#1111;$i] = $tmp;
&#125;
try that :-)

Posted: Sat Aug 03, 2002 8:34 am
by hob_goblin
btw, on the previous example, $count should be 2.. ($count will be the number of duplicates... so if i had an array with foo,foo,foo,bar ... it would be 3...)

Posted: Sat Aug 03, 2002 1:01 pm
by daemorhedron
Nice code, but what about simply using the php function array_count_values() ?

HTH!

Posted: Sat Aug 03, 2002 3:20 pm
by volka
or

Code: Select all

$c = count(array_flip($array)) // number of non-duplicate-values