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
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
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
If you are trying to count the unique values in an array, this is very straightforward and rather obvious:
echo count(array_unique($arr));