views:

377

answers:

4

How to remove duplicate values from an array in PHP and count the occurrence of every element? I have this array

  • foo
  • bar
  • foo

I want the result to be in array like this

        value   freq

        ----    ----

        foo       2

        bar       1

Thanks

A: 

To remove duplicates from the table use array_unique() function.

RaYell
thanks a lot, I knew this function but it does not count the occurrence?
ahmed
I think you will need to count those manually.
RaYell
A: 

Something like this perhaps (untested)

$freq = array();
foreach($arr as $val) {
 $freq[$val] = 0;
}
foreach($arr as $val) {
 $freq[$val]++;
}
Mark
Actually, Andrew's solution is beter. His is one pass... my head doesn't work that quick :'(
Mark
Scratch that. haim's sol'n pwns. array_count_values
Mark
+4  A: 

You want array_count_values(), followed by an array_unique().

$arr = array('foo','bar','foo');
print_r(array_count_values($arr));

$arr = array_unique($arr);
print_r($arr);

gives:

Array ( [foo] => 2 [bar] => 1 )
Array ( [0] => foo [1] => bar )
zombat
why need array_unique ? the array already unique after array_count_values
Haim Evgi
True. I had it in my head that he would need to be using the counts separate from the unique values, but you're right, `array_count_values()` does give you a unique key listing, whereas array_unique gives you a unique value listing. For ahmeds's purposes, he probably only needs `array_count_values()`.
zombat
+3  A: 

so simple , php have function

$a=array("Cat","Dog","Horse","Dog");
    print_r(array_count_values($a));

The output of the code above will be:

Array ( [Cat] => 1 [Dog] => 2 [Horse] => 1 )
Haim Evgi
omg. they have a function for that too!?
Mark
Yeah they do. =)
Alix Axel