How do I count occurrence of duplicate items in array

array_count_values, enjoy :-)

$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$vals = array_count_values($array);
echo 'No. of NON Duplicate Items: '.count($vals).'<br><br>';
print_r($vals);

Result:

No. of NON Duplicate Items: 7
Array
(
    [12] => 1
    [43] => 6
    [66] => 1
    [21] => 2
    [56] => 1
    [78] => 2
    [100] => 1
)

If you have a multi-dimensional array you can use on PHP 5.5+ this:

array_count_values(array_column($array, 'key'))

which returns e.g.

 [
   'keyA' => 4,
   'keyB' => 2,
 ]

if you want to try without 'array_count_values' you can do with a smart way here

<?php
$input= array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);

$count_values = array();
foreach ($input as $a) {

     @$count_values[$a]++;

}
echo 'Duplicates count: '.count($count_values);
print_r($count_values);
?>

Tags:

Php

Arrays

Count