Skye Bowen
Skye Bowen

Reputation: 49

In php, how do I use an increment operator in combination with a variable without it performing an increment operation?

I have a specific date - for this example say July 6. It falls in week 27 in the year 2016. Using PHP 5.5.9 I am trying to return the 7 dates that occur in that week, using the following function:

function getStartAndEndDate($week, $year) {  
    $i=0;
    $dto = new DateTime();
    $ret[$i] = $dto->setISODate($year, $week)->format('Y-m-d');
    $i++;
    while ( $i < 7 ){
        $ret[$i] = $dto->modify('+' . $i .  ' days')->format('Y-m-d');
        $i++;
    }
    return $ret;
}

I am expecting a list of 7 sequential dates from 2016-07-04 to 2016-07-10

Instead, I am receiving the following dates: 2016-07-04, 2016-07-05, 2016-07-07, 2016-07-10 2016-07-14 2016-07-19, 2016-07-25

I believe the following line is the source of my problem:

$ret[$i] = $dto->modify('+' . $i .  ' days')->format('Y-m-d');

When I specify static values, the code works.

Any suggestions, or insights would be appreciated.

Thank you

Upvotes: 0

Views: 41

Answers (2)

trincot
trincot

Reputation: 350290

The modify method really modifies $dto, so in the next iteration you're not dealing with the same $dto value as in the previous iteration.

So, actually this makes your task simpler, as you can just add 1 day every time:

$ret[$i] = $dto->modify('+1 days')->format('Y-m-d');

Upvotes: 3

Tejaswi Sharma
Tejaswi Sharma

Reputation: 158

In the line below, instead of using $i use just 1.

Your line is

$ret[$i] = $dto->modify('+' . $i .  ' days')->format('Y-m-d');

Use

$ret[$i] = $dto->modify('+1 days')->format('Y-m-d');

The reason of this is that when you use modify function it modifies the date object itself. So if initially the date was 2016-07-04 , by using modify("+$i days") [$i=1] it will 2016-07-05 but when in the next step when you do modify("+$i days") [$i=2] it will count from 2016-07-05 and will give you 2016-07-07 and this will go on.

Upvotes: 0

Related Questions