Heist Heist - 2 years ago 59
PHP Question

Count how many duplicate and unique values I have in my array

I have an array like this:

array (size=6)
0 =>
array (size=1)

'test' => string 'AQHRmVBW7uTgObjnzkqrp' (length=30)

1 => array (size=1)
'test' => string 'AQHRmU8HooJPnCKUfkGLD' (length=30)
2 =>
array (size=1)

'test' => string 'AQHRmU7+BdwM7pmpzEKew' (length=30)
3 =>
array (size=1)
'test' => string 'AQHRmU74sTU6YP4GsEee8' (length=30)
4 =>
array (size=1)
'test' => string 'AQHRmOqQAoHUgxj7T0et8' (length=30)
5 =>
array (size=1)
'test' => string 'AQHRmOqQAoHUgxj7T0et8' (length=30)

Now I want to count how many unique values there are in my array and how many duplicates I have.

As you can see the last two results are the same in the array and the other 4 are all unique. So I want my final result to be:

even: 2
uneven: 4

Answer Source
$results = array();
foreach($array as $key => $value)
     if(!isset($results[$value['test']])) $results[$value['test']]=0;

//count even and uneven
$uneven = 0;
$even = 0;
foreach($results as $key => $count)
    if($count>1) $even += $count;
    else $uneven++;

echo 'Even: '.$even.'<br>';
echo 'Uneven: '.$uneven.'<br>';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download