0

I'd like to make an array starts with the first day-o-month and finishes at the last.

$days = array();
$sdays = cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y'));
$d = new DateTime();
$d->modify('first day of this month');
for($i; $i<$sdays; $i++)
{
    $days[(int)$d->format('W')][(int)$d->format('N')] = $d->format('Y-m-d');
    $d->add(new DateInterval('P1D'));
}
print_r($days);
exit();

So it's pretty simple. But the result is looks like the DateInterval function don't work as it should.

Expectation:

Array
(
    [14] => Array // week
        (
            [1] => 2013-04-01
            [2] => 2013-04-02
            [3] => 2013-04-03
...

Reality:

Array
(
    [14] => Array
        (
            [1] => 2013-04-01
        )
)

Aye, the method, how you can fix this also simple, create an another DateTime object, modify to the first day, then create a new DateTime object from the first day, then you can add DateInterval to it.

So after i modified my DateTime object by $d->modify no date can added to it. But the question is why? I'd like to understand this.

Thanks for the answer.

Répás

Répás
  • 1,812
  • 7
  • 28
  • 54
  • As for PHP 5.4.5, your script working... `$i = 0` is the only I've fixed. And there is nothing with `$d->add(new DateInterval('P1D'))`. [***FIDDLE***](http://phpfiddle.org/main/code/y79-sr8) – BlitZ Apr 30 '13 at 10:50

1 Answers1

2

You have always use the same object, it references to the same data. You need to clone it

<?php
$days = array();
$sdays = cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y'));
$d = new DateTime();
$d->modify('first day of this month');

for($i = 0; $i<$sdays; $i++)
{
    $v = clone $d;
    $v->modify("+$i day");
    $days[(int)$v->format('W')][(int)$v->format('N')] = $v->format('Y-m-d');

}
print_r($days);
Dezigo
  • 3,220
  • 3
  • 31
  • 39