0

I have a $date variable and I like to copy his value in $date1. The problem is when I modify $date1 value with date_add() the value of $date is modified too.

How to modify only $date1 value?

<?php
$date=date_create("2013-03-15");

echo "date =>" . date_format($date,"Y-m-d");
  echo " ******** ";
$date1=$date;
date_add($date1,date_interval_create_from_date_string("40 days"));

echo "date after modify date1 =>" . date_format($date,"Y-m-d");
?>

1 Answer 1

1

In PHP objects are passed by reference. So when you assign an object to a new variable both variables refer to the same object. To avoid this, you want to clone the first object:

$date1 = clone $date;

Your code:

$date=date_create("2013-03-15");
echo "date =>" . date_format($date,"Y-m-d");
echo " ******** ";
$date1= clone $date;
date_add($date1,date_interval_create_from_date_string("40 days"));
echo "date after modify date1 =>" . date_format($date1,"Y-m-d");

Demo

You can also avoid this by using DateTimeImmutable() which will return a new DateTimeImmutable object when modified so cloning isn't necessary:

$date = new DateTimeImmutable("2013-03-15");
echo "date =>" . $date->format("Y-m-d");
echo " ******** ";
$date1 = $date->add(date_interval_create_from_date_string("40 days"));
echo "date after modify date1 =>" . $date1->format("Y-m-d");

Demo

1
  • Thank you very much Mr John, your answer is useful and solved the problem.
    – symfony
    Jan 4, 2021 at 12:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.