0

I need to know the number of different values in an array. For example if it contains (5, 5, 5) then I should get 1. If it contains (4, 4, 2, 2) I should get 2. If (5, 5, 5, 5, 2, 2, 1, 5) then 3.

Is there a function that can achieve that directly in PHP?

3 Answers 3

2

echo count(array_unique($arr));

you can use array_unique which returns unique elements of array (result is also array type) and then count on result

Sign up to request clarification or add additional context in comments.

Comments

1

Two simple ways to achieve that:

  • $diff_count = count(array_unique($input_arr));
  • $diff_count = count(array_flip($input_arr)); <-- recommended (performance)

array_unique() :

Removes duplicate values from an array - you can add adittional flags such as:

  • SORT_REGULAR - compare items normally (don't change types)
  • SORT_NUMERIC - compare items numerically
  • SORT_STRING - compare items as strings
  • SORT_LOCALE_STRING - compare items as strings, based on the current locale.

array_flip():

Exchanges all keys with their associated values in an array - so duplicates keys are overwritten and you get a final array with the unique values as keys.

Flipping it twice will result in an array with unique values and the highest keys there were in the original input array.

More reading:

Benchmark:

Since the array_flip uses only O(n) exactly its much faster - using an array of 10,000 numbers as an input:

  • array_unique + count: ~28.615 ms.
  • array_flip + count: ~0.5012 ms. (winner)

Comments

0

Is there a function that can achieve that directly in PHP?

The closest one would be array_unique() but here is a simple function to achieve what you are looking for:

$arr = array(5,5,5,5,2,2,1,5);

function array_diff_values( $array ) {
    return count( array_unique($array) );
}

$count = array_diff_values( $arr );

result of $count is 3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.