0

I'm struggling with how to build the following:

result I need:

$months = array();
$months
(
    month[0] = '2011-10-1'
    month[1] = '2011-11-1'
    month[2] = '2011-12-1'
    month[3] = '2012-1-1'
)

from the following variables:

$date = '2011-10-1';
$numberOfMonths = 4; 

Any help would be appreciated.

Thanks, guys... all of these solutions work. I accepted the one that works best for my usage.

4 Answers 4

2

You can do it using a simple loop and strtotime():

$date = '2011-10-1';
$numberOfMonths = 4; 

$current = strtotime($date);
$months = array();
for ($i = 0; $i < $numberOfMonths; $i++) {
  $months[$i] = date('Y-n-j', $current);
  $current = strtotime('+1 month', $current);
}
Sign up to request clarification or add additional context in comments.

1 Comment

@nachito: Good lord it's been a long week! Thanks for pointing that out, fixed :-)
1
$date = DateTime::createFromFormat('Y-m-j', '2011-10-1');

$months = array();
for ($m = 0; $m < $numberOfMonths; $m++) {
   $next = $date->add(new DateInterval("P{$m}M"));
   $months[] = $next->format('Y-m-j');
}

1 Comment

Good solution for PHP >= 5.3.0
0
<?php
function getNextMonths($date, $numberOfMonths){
    $timestamp_now = strtotime($date);
    $months[] = date('Y-m-d', $timestamp_now);
    for($i = 1;$i <= $numberOfMonths; $i++){
          $months[] = date('Y-m-d', (strtotime($months[0].' +'.$i.' month')));
    }
    print_r($months);
}
getNextMonths('2011-10-1', 4);

Working demo

Comments

0

You could use split on date and then a for loop over the month. The trick is to use something like

$newMonth = ($month + $i) % 12 + 1;

(% is called modulo and does exactly what you want.)

2 Comments

This does not take care of the next year?
No, but you can just increment the year when $month == 1

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.