+4 votes
in Programming Languages by (63.4k points)

I want to count the occurrence of each element of a PHP array. How can I count it?


In the following array,  count of "A" is 2.


1 Answer

+2 votes
by (271k points)
selected by
Best answer

You can use PHP function array_count_values() to calculate the occurrence/frequency of each element of an array.

Here is your example:

I have used PHP terminal and hence all statements start with "php >".

php > $a=array("A","B","B","C","A","D","D","B");
php > print_r(array_count_values($a));
    [A] => 2
    [B] => 3
    [C] => 1
    [D] => 2