+2 votes
in Programming Languages by (15.0k points)

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

E.g.

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

array("A","B","B","C","A","D","D","B")

1 Answer

0 votes
by (25.1k points)

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));
Array
(
    [A] => 2
    [B] => 3
    [C] => 1
    [D] => 2
)

...