php - Count surplus entries of duplicate values in an array

512

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] 
342

Answer

Solution:

You can combine{-code-1} andarray_count_values

$counts = array_count_values({-code-1}($array, 'KRA_category'));

ForBusiness you would then use

$business_count = $counts['Business'] - 1;

to get the duplicates.-1 is to ignore the original and only count the extras.

814

Answer

Solution:

you can count the duplicate values in php with

$vals = array_count_values(array_column($array, 'KRA_category'));

supported in 5.5 and above.

960

Answer

Solution:

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)
        )
    )
);

People are also looking for solutions to the problem: php - modal, button on modal executing many time

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.