Search code examples
phparray-unique

Displaying number of instances of each array value


$myArray = array(2, 7, 4, 2, 5, 7, 6, 7);

$uniques = array_unique($myArray);

Along with displaying each value in the array only once, how would I ALSO display (in the foreach loop below) the number of times each value is populated in the array. IE next to '7' (the array value), I need to display '3' (the number of times 7 is in the array)

foreach ($uniques as $values) {
echo $values . " " /* need to display number of instances of this value right here */ ;
}

Solution

  • Use the array_count_values function instead.

    $myArray = array(2, 7, 4, 2, 5, 7, 6, 7);
    $values = array_count_values($myArray);
    foreach($values as $value => $count){
    echo "$value ($count)<br/>";
    }