2

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
1
  • 1
    you count the number of time 09 is in archive_months => 1 Commented Sep 24, 2020 at 13:24

3 Answers 3

3

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)
}
Sign up to request clarification or add additional context in comments.

Comments

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));

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.