Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a clever way to count number of unique items in array (PHP)? [duplicate]

Tags:

php

Possible Duplicate:
Unique entries in an array

Let assume the array is sorted, how can I get number of counts for each unique items

Example:

  $array = array ("bye", "bye", "bye", "hello", "hello");

Output:

    bye   = 3
    hello = 2 
like image 204
Cory Avatar asked Apr 05 '11 14:04

Cory


People also ask

How do you count the number of unique values in an array?

You can use the combination of the SUM and COUNTIF functions to count unique values in Excel. The syntax for this combined formula is = SUM(IF(1/COUNTIF(data, data)=1,1,0)). Here the COUNTIF formula counts the number of times each value in the range appears. The resulting array looks like {1;2;1;1;1;1}.

How do I count occurrence of duplicate items in 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 .

How do I count items in an array PHP?

How to Count all Elements or Values in an Array in PHP. We can use the PHP count() or sizeof() function to get the particular number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that we can initialize with an empty array.

How can I get only duplicate values from an array in PHP?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.


1 Answers

If you want to get the total count of unique values in a specified column within a given array, as a simple integer (rather than another array) try something simple like this:

$uniqueCount = count(array_unique(array_column($data, 'column_name'))); 

// (where $data is your original array, and column_name is the column you want to cycle through to find the total unique values in whole array.)  

var_dump(array_count_values(array("bye", "bye", "bye", "hello", "hello")));
like image 109
Stefan Gehrig Avatar answered Oct 18 '22 10:10

Stefan Gehrig