how to count values from an array and show value only once in a foreach loop

Viewed 491

I am struggling with this problem: I have an array with months as values. In the array are 3 values(months): 09, 09 and 04. So 2 times the month September (09) and 1 time the month April (04).

Now i want to output each month only once and the number of times that the month occurs behind it. So my output in this should look like

04 1 // april 1 time
09 2 // september 2 times

I now have this foreach loop:

$months = array('04','09','09');
foreach($months as $month) {                
    $archive_months = array('01','02','03','04','05','06','07','08','09','10','11','12'); 
    $counts = array_count_values($archive_months);
    echo $month.' '.$counts[$month].'<br />';

if i use foreach(array_unique($months) as $month) { the month september (09) appears only once but the number is 1 and not 2.

Output:

04 1
09 1

And it should be:

04 1
09 2
3 Answers

Just count values of months not archive_months

<?php

$months = array('04','09','09');
 
$counts = array_count_values($months);
var_dump($counts);

output:

array(2) {
  ["04"]=>
  int(1)
  ["09"]=>
  int(2)
}

You're not counting $months, but $archive_months.

And arry_count_values is already doing what you need. No for loop needed.

$months = array('04','09','09');
print_r(array_count_values($months));

Like Ôrel already mentioned:

$months = array('04','09','09'); 
$counts = array_count_values($months);

// your foreach:
foreach($counts as $key => $val) {
    echo $key.' '.$val.'<br />';
}

Output will be something like:

09 2
04 1
Related