How to remove duplicate values ​​from an array in PHP and count occurrence?

How to remove duplicate values ​​from an array in PHP and count the appearance of each element? I have this array

  • Foo
  • bar
  • Foo

I want the result to be in an array like this

        value   freq

        ----    ----

        foo       2

        bar       1

thanks

+3
source share
4 answers

so simple php have function

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

Code output above:

Array ( [Cat] => 1 [Dog] => 2 [Horse] => 1 )  
+7
source

You want array_count_values ​​() and then 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 ) 
+5
source

To remove duplicates from a table, use array_unique () .

+1
source

Something like this is possible (unverified)

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

Source: https://habr.com/ru/post/1714375/


All Articles