ahmed
ahmed

Reputation: 14666

Count the occurrences of each value in an array

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

I want the result to be in array like this

        value   freq

        ----    ----

        foo       2

        bar       1

Thanks

Upvotes: 3

Views: 3362

Answers (3)

Haim Evgi
Haim Evgi

Reputation: 125456

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 )  

Upvotes: 7

zombat
zombat

Reputation: 94147

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 ) 

Upvotes: 5

mpen
mpen

Reputation: 282825

Something like this perhaps (untested)

$freq = array();
foreach($arr as $val) {
    $freq[$val] = 0;
}
foreach($arr as $val) {
    $freq[$val]++;
}

Upvotes: 0

Related Questions