0

For the code below i want to have the current month and the next 12 months with the year. Im using a loop for it, everyting works fine except for "January". And i just don't know whats going wrong.

for ($i = 0; $i <= 12; $i++) {
    $months[ucfirst(strftime("%B %G", strtotime( date( 'Y-m' )." +$i months")))] = ucfirst(strftime("%B %G", strtotime( date( 'Y-m' )." +$i months")));
    echo ucfirst(strftime("%B %G", strtotime( date( 'Y-m' )." +$i months")));
}

The echo output:

December 2015 Januari 2015 Februari 2016 Maart 2016 April 2016 Mei 2016 Juni 2016 Juli 2016 Augustus 2016 September 2016 Oktober 2016 November 2016 December 2016
3
  • Try using date('M-y') rather than ('Y-m')
    – Fredrik
    Commented Dec 15, 2015 at 11:08
  • Tip: don't abuse strings when doing calculations of any kind (including time). Commented Dec 15, 2015 at 11:09
  • @Fredrik thanks, its has worked. But why was mine wrong?
    – Carl0s1z
    Commented Dec 15, 2015 at 11:11

2 Answers 2

3

What about something like this?

<?php

$start = new DateTimeImmutable('first day of this month');
$interval = new DateInterval('P1M');
$period = new DatePeriod($start, $interval, 12);

foreach ($period as $date) {
    echo $date->format('F Y') . PHP_EOL;
}
2

You can simply use:

$date = new DateTime('first day of this month');

for ($i = 0; $i < 13; $i++) {
    echo $date->format('F Y,');
    $date->modify('+1 month');
}

The output would be:

December 2015, January 2016, February 2016, March 2016, April 2016, May 2016, June 2016, July 2016, August 2016, September 2016, October 2016, November 2016, December 2016,

3
  • Im sorry but a needed it in Dutch and in a var for select (in a form). The solution from Frederik Worked fine.
    – Carl0s1z
    Commented Dec 15, 2015 at 11:22
  • If the current date is towards the end of the month, you can have problems with skipping months. For example, setting $date = new DateTime('2015-12-31')' will skip February. You need to make sure it's the start of the month.
    – Dezza
    Commented Dec 15, 2015 at 11:23
  • 1
    I've just verified and you're right.. I've just updated my answer. Thanks. Your answer is pretty good as well :) Commented Dec 15, 2015 at 11:25

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.