I need count of duplicate values in my array.
[
['KRA_category' => 'Business'],
['KRA_category' => 'Business'],
['KRA_category' => 'People'],
['KRA_category' => 'Business'],
['KRA_category' => 'Business'],
['KRA_category' => 'Business'],
];
Expected result:
['Business' => 4]
3 Answers 3
You can combine array_column and array_count_values
$counts = array_count_values(array_column($array, 'KRA_category'));
For Business you would then use
$business_count = $counts['Business'] - 1;
to get the duplicates. -1 is to ignore the original and only count the extras.
9 Comments
i need count of duplicate values in array for e.g. business=4.array_walk() to decrement, but it felt too messy to me.you can count the duplicate values in php with
$vals = array_count_values(array_column($array, 'KRA_category'));
supported in 5.5 and above.
1 Comment
i need count of duplicate values in array for e.g. business=4.To reduce the total cycles needed to isolate the elements that occur more than once, I'll demonstrate a foreach loop that will initialize a lookup array with a -1 value then increment it for every occurrence.
array_filter() is called to remove entries in the lookup which only got up to 0. This will leave only values that have a positive count after excluding the first occurrence.
Code: (Demo) (Alternative Syntax)
$array = [
['KRA_category'=>'Business'],
['KRA_category'=>'Business'],
['KRA_category'=>'People'],
['KRA_category'=>'Business'],
['KRA_category'=>'Business'],
['KRA_category'=>'Business']
];
foreach ($array as ['KRA_category' => $value]) {
$result[$value] ??= -1;
++$result[$value];
}
var_export(array_filter($result));
Output:
array (
'Business' => 4,
)
You can achieve the same result with a functional-style approach but this will require far greater computational time complexity. (Demo)
var_export(
array_count_values(
array_diff_key(
array_column($array, 'KRA_category'),
array_unique($array, SORT_REGULAR)
)
)
);
array_count_valuescan't be used for multi-dimensional arrays.business = 4? There are 5 elements withKRA_category => Business.