Reputation: 339
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);
Upvotes: 0
Views: 1573
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
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);
Upvotes: 1