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

Wicher Visser
  • 1,513
  • 12
  • 21
montblanc
  • 13
  • 7
  • 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`. – kainaw Jun 06 '16 at 14:45

2 Answers2

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

Steve
  • 20,703
  • 5
  • 41
  • 67
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));
kainaw
  • 4,256
  • 1
  • 18
  • 38
  • 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 – Steve Jun 06 '16 at 14:49
  • 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. – kainaw Jun 06 '16 at 14:50
  • Fair enough, i wasnt suggesting flip was better, quite the opposite, though a quick google has suggested my brain wasnt completely broken: http://stackoverflow.com/questions/8321620/array-unique-vs-array-flip i must have come to this conclusion in the past but forgot why – Steve Jun 06 '16 at 14:51
  • 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. – kainaw Jun 06 '16 at 14:54