How to count the number of duplicate keys in an array?

Is it possible to get how much "a" is in the array?

$array = array( 'a', 'a', 'a', 'a', 'b', 'b', 'c' );
+3
source share
3 answers

Since you are just looking for values a, you can also use array_keys:

$array = array( 'a', 'a', 'a', 'a', 'b', 'b', 'c' );
$count = count(array_keys($array, 'a', true));
echo "Found $count letter a's.";
+3
source

array_count_values - this is what you need

<?php
$array = array( 'a', 'a', 'a', 'a', 'b', 'b', 'c' );
print_r(array_count_values($array));
?>

The above example outputs:

Array
(
    [a] => 4
    [b] => 2
    [c] => 1
)
+11
source

Chaim is right. However, I used to have problems with array_count_values ​​parameters. Therefore, if you already know what value you are checking, and do not need others. The cycle and counter can be faster. I would appreciate it.

EDIT

That is, if the array is less than 1000-10 000 elements. Then it is probably too small to make a difference.

+2
source

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


All Articles