Skye Bowen Skye Bowen - 2 months ago 7x
PHP Question

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) {
$dto = new DateTime();
$ret[$i] = $dto->setISODate($year, $week)->format('Y-m-d');
while ( $i < 7 ){
$ret[$i] = $dto->modify('+' . $i . ' days')->format('Y-m-d');
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


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

Your line is

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


$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.