Get the total of each unique value in an array?

Ok, so I have an array that has a ton of random numbers in it, for example ...

$array = array(134, 12, 54, 134, 22, 22, 1, 9, 45, 45, 12, 134, 45, 134); 

What I need to do is figure out what numbers are in my array, and if the number is duplicated in the array, I would like to know how many times this number is found in the array. Therefore, taking the array I listed above, I need the results to be something like this:

 134: 4 12: 2 54: 1 22: 2 1: 1 9: 1 45: 3 etc. 

Any bright ideas on how to do this?

Thanks!

+4
source share
3 answers

See array_count_values .

 <?php print_r(array_count_values( array(134, 12, 54, 134, 22, 22, 1, 9, 45, 45, 12, 134, 45, 134))); 

gives:

  Array
 (
     [134] => 4
     [12] => 2
     [54] => 1
     [22] => 2
     [1] => 1
     [9] => 1
     [45] => 3
 )
+8
source

Use array_count_values() to count the occurrence of each unique value:

 $counts = array_count_values($array); var_dump($counts); 

Conclusion:

 array(7) { [134]=> int(4) [12]=> int(2) [54]=> int(1) [22]=> int(2) [1]=> int(1) [9]=> int(1) [45]=> int(3) } 
+2
source

You can use the function:

 array_count_values($array) 
+2
source

All Articles