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

Solution 1:

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")));

Solution 2:

You can use array_count_values.

print_r(array_count_values($array));

will return :

Array
(
    [bye] => 3
    [hello] => 2
)

Solution 3:

You can use array_count_values on your array which would return something like:

array(2){
    ["bye"]=> int(3)
    ["hello"]=> int(2)
}

Example Usage:

$unique = array_count_values($my_array);