Friday 31 August 2018

PHP putting four dates in an array from a while loop

Using the below while loop, I get four dates in the echo, which is what I need.

$data = [];

$start = Carbon::createFromDate('2016', '04', '01');
$end = Carbon::createFromDate('2017', '04', '01');

while($start < $end)
{
    $data[] = $start;

    echo $start;

    $start->addMonths('3');
}

Output:
2016-04-01
2016-07-01
2016-10-01
2017-01-01

But when I dump the $data[] array, I just get four collections, each with the same date:
2017-04-01

What am I doing wrong? I just want to put the above four dates in an array.

You're assigning an object instance ($start) to each array entry (and objects are "by reference"), and modifying that object instance, so the same object instance is being changed wherever.... assign a "clone" into your array
while($start < $end)
{
    $data[] = clone $start;
    echo $start;
    $start->addMonths('3');
}

0 comments:

Post a Comment