67

I would like to count the occurrence of each duplicate item in an array and end up with an array of only unique/non duplicate items with their respective occurrences.

Here is my code; BUT I don't where am going wrong!

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

//$previous[value][Occurrence]

for($arr = 0; $arr < count($array); $arr++){

    $current = $array[$arr];
    for($n = 0; $n < count($previous); $n++){
        if($current != $previous[$n][0]){// 12 is not 43 -----> TRUE
            if($current != $previous[count($previous)][0]){
                $previous[$n++][0] = $current;
                $previous[$n++][1] = $counter++;
            }
        }else{  
            $previous[$n][1] = $counter++;
            unset($previous[count($previous)-1][0]);
            unset($previous[count($previous)-1][1]);
        }   
    }
}
//EXPECTED VALUES
echo 'No. of NON Duplicate Items: '.count($previous).'<br><br>';// 7
print_r($previous);// array( {12,1} , {21,2} , {43,6} , {66,1} , {56,1} , {78,2} , {100,1})
?>    
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
mukamaivan
  • 1,435
  • 6
  • 16
  • 24

13 Answers13

191

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
)
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • 3
    then array_keys($array) to get the desired output array; PS you all need to work on your variable naming – David Chan Nov 29 '12 at 20:19
  • 1
    It's worth noting that this only works on integers and strings. If you have an array of arrays or objects you will need to iterate through your array yourself, counting duplicates. – Juniper Jones Jun 24 '18 at 23:19
12

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);
?>
Sam Arul Raj T
  • 1,752
  • 17
  • 23
  • 1
    Hi Sam T. I like your method how to you done in smart way. Can you please explain me @$count_values[$a]++; what @ represent and what it does, Thanks your – jvk Feb 24 '17 at 13:13
  • 2
    @KrishnaJonnalagadda it just suppresses the warnings. – Sam Arul Raj T Jan 17 '20 at 09:15
  • Error suppressors give code an immediate smell. I advise that developers avoid this technique as much as possible and instead handle notices and warnings properly. I would never deem this to be "the smart way". – mickmackusa Jul 17 '22 at 21:41
7

Simplest solution (that's where PHP rocks) - ONLY duplicates:

$r = array_filter(array_count_values($array), function($v) { return $v > 1; });

and check:

print_r($r);

Result $r:

[43] => 6
[21] => 2
[78] => 2
forsberg
  • 1,681
  • 1
  • 21
  • 27
4

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,
 ]
PHZ.fi-Pharazon
  • 1,479
  • 14
  • 15
2

I actually wrote a function recently that would check for a substring within an array that will come in handy in this situation.

function strInArray($haystack, $needle) {
    $i = 0;
    foreach ($haystack as $value) {
        $result = stripos($value,$needle);
        if ($result !== FALSE) return TRUE;
        $i++;
    }
    return FALSE;
}

$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);

for ($i = 0; $i < count($array); $i++) {
    if (strInArray($array,$array[$i])) {
        unset($array[$i]);
    }
}
var_dump($array);
WhoaItsAFactorial
  • 3,538
  • 4
  • 28
  • 45
  • This answer does not resolve the asked question. This is, at best, the correct answer to a different question. https://3v4l.org/XqgDA – mickmackusa Jul 17 '22 at 21:39
2

You can also use it with text items array, u will get number of duplicates properly, but PHP shows

Warning: array_count_values(): Can only count STRING and INTEGER values!

$domains = 
array (
  0 => 'i1.wp.com',
  1 => 'i1.wp.com',
  2 => 'i2.wp.com',
  3 => 'i0.wp.com',
  4 => 'i2.wp.com',
  5 => 'i2.wp.com',
  6 => 'i0.wp.com',
  7 => 'i2.wp.com',
  8 => 'i0.wp.com',
  9 => 'i0.wp.com' );

$tmp = array_count_values($domains);
print_r ($tmp);

    array (
      'i1.wp.com' => 2730,
      'i2.wp.com' => 2861,
      'i0.wp.com' => 2807
    )
wtfowned
  • 124
  • 1
  • 11
2

Count duplicate element of an array in PHP without using in-built function

$arraychars=array("or","red","yellow","green","red","yellow","yellow");
$arrCount=array();
        for($i=0;$i<$arrlength-1;$i++)
        {
          $key=$arraychars[$i];
          if($arrCount[$key]>=1)
            {
              $arrCount[$key]++;
            } else{
              $arrCount[$key]=1;
        }
        echo $arraychars[$i]."<br>";
     }
        echo "<pre>";
        print_r($arrCount);
Rupesh Wankhede
  • 457
  • 5
  • 16
1

There is a magical function PHP is offering to you it called in_array().

Using parts of your code we will modify the loop as follows:

<?php
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$arr2 = array();
$counter = 0;
for($arr = 0; $arr < count($array); $arr++){
    if (in_array($array[$arr], $arr2)) {
        ++$counter;
        continue;
    }
    else{
        $arr2[] = $array[$arr];
    }
}
echo 'number of duplicates: '.$counter;
print_r($arr2);
?>

The above code snippet will return the number total number of repeated items i.e. form the sample array 43 is repeated 5 times, 78 is repeated 1 time and 21 is repeated 1 time, then it returns an array without repeat.

SaidbakR
  • 13,303
  • 20
  • 101
  • 195
  • Dear researchers, using iterated calls of `in_array()` is one of worst options for this task in terms of performance. – mickmackusa Oct 23 '21 at 03:54
1

I came here from google looking for a way to count the occurrence of duplicate items in an array. Here is the way to do it simply:

$colors = ["red", "green", "blue", "red", "yellow", "blue"];

$unique_colors = array_unique($colors);                // ["red", "green", "blue", "yellow"]
$duplicates = count($colors) - count($unique_colors);  // 6 - 4 = 2

if ($duplicates == 0) {
    echo "There are no duplicates";
}
echo "No. of Duplicates: " . $duplicates;

// Output: No. of Duplicates are: 2

How array_unique() works?

It elements all the duplicates. ex: Lets say we have an array as follows -

$cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [3]=>"ferrari", [4]=>"Bugatti");

When you do $cars = array_unique($cars); cars will have only following elements. $cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [4]=>"Bugatti");

To read more: https://www.php.net/manual/en/function.array-unique.php

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Sahith Vibudhi
  • 4,935
  • 2
  • 32
  • 34
1

You can do it using foreach loop. (Demo)

$array = array(1,2,3,1,2,3,1,2,3,4,4,5,6,4,5,6,88);
$set_array = array();
foreach ($array as $value) {
    $set_array[$value]++;
}
print_r($set_array);     

Output:

Warning: Undefined array key 1 in /in/aGPqe on line 6

Warning: Undefined array key 2 in /in/aGPqe on line 6

Warning: Undefined array key 3 in /in/aGPqe on line 6

Warning: Undefined array key 4 in /in/aGPqe on line 6

Warning: Undefined array key 5 in /in/aGPqe on line 6

Warning: Undefined array key 6 in /in/aGPqe on line 6

Warning: Undefined array key 88 in /in/aGPqe on line 6
Array
(
    [1] => 3
    [2] => 3
    [3] => 3
    [4] => 3
    [5] => 2
    [6] => 2
    [88] => 1
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
user3040433
  • 85
  • 2
  • 4
0

this code will return duplicate value in same array

$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
foreach($arr as $key=>$item){
  if(array_count_values($arr)[$item] > 1){
     echo "Found Matched value : ".$item." <br />";
  }
}
Salman Saleem
  • 439
  • 4
  • 14
  • Um, what? https://3v4l.org/C3dLj Did you test this before posting? Why would you ask PHP to perform the same function execution on the same re-encountered value in `$array`? – mickmackusa Jul 17 '22 at 21:33
-1
$search_string = 4;
$original_array = [1,2,1,3,2,4,4,4,4,4,10];
$step1 = implode(",", $original_array); // convert original_array to string
$step2 = explode($search_string, $step1); // break step1 string into a new array using the search string as delimiter
$result = count($step2)-1; // count the number of elements in the resulting array, minus the first empty element
print_r($result); // result is 5
-2
    $input = [1,2,1,3,2,4,10];
    //if give string
    //$input = "hello hello how are you how hello";
    //$array = explode(' ',$input);
    $count_val = [];
    foreach($array as $val){
      $count_val[$val]++;
    }
    print_r($count_val);
//output ( [1] => 2 [2] => 2 [3] => 1 [4] => 1 [10] => 1 )