
Question:
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);
<blockquote>
total = 4
</blockquote> Answer1: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:
<a href="http://php.net/manual/en/function.array-flip.php" rel="nofollow">http://php.net/manual/en/function.array-flip.php</a>
<blockquote>If a value has several occurrences, the latest key will be used as its value, and all others will be lost.
</blockquote>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
If you are trying to count the unique values in an array, this is very straightforward and rather obvious:
echo count(array_unique($arr));