Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count occurrence of duplicate items in array

Tags:

arrays

php

count

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}) ?>     
like image 248
mukamaivan Avatar asked Nov 29 '12 20:11

mukamaivan


People also ask

How do you count duplicates in an array?

To count the duplicates in an array: Declare an empty object variable that will store the count for each value. Use the forEach() method to iterate over the array. On each iteration, increment the count for the value by 1 or initialize it to 1 .


1 Answers

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 ) 
like image 88
Rocket Hazmat Avatar answered Oct 20 '22 12:10

Rocket Hazmat