Question

$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 */ ;
}
Was it helpful?

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/>";
}

OTHER TIPS

Have a look at array_count_values.

Quoting from the manual:

Example #1 array_count_values() example

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

The above example will output:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top