Ishikawa
Ishikawa

Reputation: 177

Looping through an array with PHP

I want to use PHP to populate an array starting with today's date and going several days into the future. When I tried the following below all of the columns contain "2013-11-18." I have been toying with it for 2 hours, but to no avail. What am I missing?

//Get "Day 0", today if undefined
if(isset($_GET['DAY0']) == TRUE){
    $day0 = new DateTime($_GET['DAY0']);
} else {
    $day0 = new DateTime('today');
}

    // save day0 + 7 days into into dayArray
    $dayArray[0] = $day0;
    for($i=1; $i<8; $i++){
        $day0->modify('+1 day');
        $dayArray[i]= $day0;
    }

    echo "<tr>"; 
    for ($i = 0; $i < 7; $i++) {
        echo "<th>".$dayArray[i]->format('Y-m-d')."</th>";
    }
    echo "</tr>";

Upvotes: 2

Views: 121

Answers (4)

Rob
Rob

Reputation: 12872

Objects are passed by reference. You are assigning multiple references to the same object in your array.

If you really need all the datetime objects in the array, you could do something like this

$interval = new DateInterval('P1D');
$start = new DateTime('today');

$dayArray = [clone $start];

for ($i = 1; $i < 8; $i++) {
    $dayArray[] = clone $start->add($interval);
}

Or you could just store the formatted dates as already suggested.

$interval = new DateInterval('P1D');
$start = new DateTime('today');

$dayArray = [$start->format('Y-m-d')];

for ($i = 1; $i < 8; $i++) {
    $dayArray[] = $start->add($interval)->format('Y-m-d');
}

Upvotes: 2

Tom
Tom

Reputation: 622

You can create a DatePeriod like so:

    if(isset($_GET['DAY0']) == TRUE){
        $day0 = new DateTime($_GET['DAY0']);
    } else {
        $day0 = new DateTime('today');
    }

    $enddate = new DateTime();

    $period = new DatePeriod(
            $day0,
            new DateInterval('P1D'),
            $enddate->add(new DateInterval('P7D'))
    );

    echo "<tr>";
      foreach ($period as $datetime) {
         echo "<th>".datetime->format('Y-m-d')."</th>";

      }
    echo "</tr>";

Upvotes: 0

Mihai Iorga
Mihai Iorga

Reputation: 39724

You could save timestamps:

// save day0 + 7 days into into dayArray
$dayArray[0] = $day0->format('U');
for($i=1; $i<8; $i++){
    $day0->modify('+1 day');
    $dayArray[$i] = $day0->format('U');
}

echo "<tr>"; 
for ($i = 0; $i < 7; $i++) {
    echo "<th>".date('Y-m-d', $dayArray[$i])."</th>";
}

Upvotes: 0

Paul Lo
Paul Lo

Reputation: 6148

Replace two of your $dayArray[i] with $dayArray[$i]

Upvotes: 0

Related Questions