lukasz
lukasz

Reputation: 339

Array of the DateTime object

Why all the dates in array are the same? var_dump works OK

$start = new DateTime('01-01-2014');
$end = new DateTime('07-01-2014');
$dates = array();

do {
var_dump($start);
array_push($dates, $start);
$start->add(DateInterval::createFromDateString('1 day'));
}
while ($start != $end);

print_r($dates);

http://ideone.com/XV9I4C

Upvotes: 0

Views: 1573

Answers (2)

Kevin Sandow
Kevin Sandow

Reputation: 4033

The array you create contains multiple references to the same object (the one you created with $start = new DateTime('01-01-2014');, thus they are all the same. var_dump only works because it outputs the current date of the objects.

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212442

Because start is still the same object instance in every element of the array: you're pushing multiple pointers to the same instance, not multiple instances

$start = new DateTime('01-01-2014');
$end = new DateTime('07-01-2014');
$dates = array();

do {
var_dump($start);
array_push($dates, clone $start);
$start->add(DateInterval::createFromDateString('1 day'));
}
while ($start != $end);

print_r($dates);

DEMO

Upvotes: 1

Related Questions