0

I am looping through a for-loop to fill an array with dates. With each iteration I want to increase the date variable by one day.

$myDate = date_create(date_default_timezone_get());
$myArr;
for ($i = 0; $i <= 1; $i++) {
    $myArr[$i] = $myDate;
    $myDate->modify('+1 day');
}

What it returns to me if the current date is 06-November-2021:

echo date_format($myArr[0], 'd.m.Y'); //08.11.2021
echo date_format($myArr[1], 'd.m.Y'); //08.11.2021

I would expect that it returns 06.11.2021 and 07.11.2021 but it seems it uses some kind of references instead of values in my array. Can someone explain?

Julian
  • 185
  • 1
  • 15
  • In PHP, as in many other languages, objects are passed by reference. So you're adding and modifying the same object instance. Please check the [clone](https://www.php.net/manual/en/language.oop5.cloning.php) operator. – Álvaro González Nov 06 '21 at 09:58
  • "seems it uses some kind of references" -- use https://www.php.net/manual/en/function.spl-object-id to find out yourself. – Ulrich Eckhardt Nov 06 '21 at 10:37
  • I am not really used to PHP programming but I found this thread and thought this would count in general: https://stackoverflow.com/questions/879/are-php-variables-passed-by-value-or-by-reference – Julian Nov 06 '21 at 10:58
  • If you don't need the date object anymore, you should format the date inside your loop and assign the formated string to your array. – Mujnoi Gyula Tamas Nov 06 '21 at 11:02

1 Answers1

2

you should create a new date and assign it to array try this

<?php
$myDate = date_create(date_default_timezone_get());
$myArr;
for ($i = 0; $i <= 4; $i++) {
    $myArr[$i] = date_create(date_format($myDate,'d.m.Y'));
    $myDate->modify('+1 day');
}

echo "<pre>";
print_r($myArr);
echo "</pre>";
?>

result

enter image description here