0

I have an array like this

$arr = array(1,2,1,3,2,4);

How to count total of variant data from that array ?

example :

$arr = array(1,2,1,3,2,4);

total = 4

1
  • Are you trying to count the number of unique values in an array? Have you considered looking at the PHP documentation? Specifically, array_unique and count. Commented Jun 6, 2016 at 14:45

2 Answers 2

1

You can flip the array, and check its length:

echo count(array_flip($arr));

This works because an array index must be unique, so you end up with one element for every unique item in the original array:

http://php.net/manual/en/function.array-flip.php

If a value has several occurrences, the latest key will be used as its value, and all others will be lost.

This is (was?) somewhat faster than array_unique, but unless you are calling this a LOT, array_unique is a lot more descriptive, so probably the better option

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

Comments

1

If you are trying to count the unique values in an array, this is very straightforward and rather obvious:

echo count(array_unique($arr));

4 Comments

Ha, good point, no idea why my brain landed on using a side effect from array_flip when array_unique is clearly designed for the task
I didn't want to use array_flip because it will change the value in rare cases. Example: "04" and "4" will both become integer 4.
Fair enough, i wasnt suggesting flip was better, quite the opposite, though a quick google has suggested my brain wasnt completely broken: stackoverflow.com/questions/8321620/array-unique-vs-array-flip i must have come to this conclusion in the past but forgot why
Correct. array_flip is faster. Also, the error is rare. If the values are all integers, then array_flip is better. I just don't know the scope of the true problem and my main point is that the person should make some attempt to read the documentation before asking a question. count and array_unique should be very easy to find.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.