counting duplicate elements in 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
sebamed
Forum Newbie
Posts: 4
Joined: Mon Jul 08, 2002 9:23 am

counting duplicate elements in array

Post 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]++;
}
User avatar
hob_goblin
Forum Regular
Posts: 978
Joined: Sun Apr 28, 2002 9:53 pm
Contact:

Post 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 :-)
User avatar
hob_goblin
Forum Regular
Posts: 978
Joined: Sun Apr 28, 2002 9:53 pm
Contact:

Post 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...)
daemorhedron
Forum Commoner
Posts: 52
Joined: Tue Jul 23, 2002 11:03 am

Post by daemorhedron »

Nice code, but what about simply using the php function array_count_values() ?

HTH!
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

or

Code: Select all

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