0

I have a sort array of dates. I want to go from a specific begin date to a specific end date, and increment a variable each time I find the given date in the array. Í tried with the following code snippet:

$result = array();  
$iterator = 0;
for ($minDateTime = new DateTime($minDate); $minDateTime <= new DateTime($maxDate);  $minDateTime->add(new DateInterval('P01D'))) {
    if ($minDateTime = $myDateArray[$iterator]) {
        $iterator++;
    }
    array_push($result, "$minDateTime=>$iterator");
}

If I want to run this code I got the following error:

Fatal error: Call to a member function add() on a non-object in /home/pivoecom/public_html/teszt/query_test.php on line 34

Where line 34 is the opening of the for cycle. I read the reference of DateTime and I'm sure that there is an add method for it. I tried to add day with this line outside the for cycle and it worked... What do I do wrong?

vascowhite
  • 18,120
  • 9
  • 61
  • 77
zsidanyi
  • 105
  • 1
  • 2
  • 6
  • This seems quite puzzling. Although a seeming logical error was observed with this method http://stackoverflow.com/questions/9282287/what-can-go-wrong-when-adding-months-with-a-dateinterval-and-datetimeadd, this seems to be more puzzling. Are you sure it works if you shift that `add` call outside of loop? – verisimilitude Aug 31 '13 at 10:42
  • I'm sure. I tried it because a thought that my webservers has a too old PHP on it. But it worked. – zsidanyi Aug 31 '13 at 11:22

1 Answers1

0

Your code will work if you remove the typo:-

if ($minDateTime = $myDateArray[$iterator]) {

Should be:-

if ($minDateTime == $myDateArray[$iterator]) {

Or, possibly:-

if ($minDateTime === $myDateArray[$iterator]) {

I like the way you have set up the loop, I've never thought of doing that, I shall definately be using it in the future, however I'll probably do:-

for ($minDateTime = new DateTime($minDate), $maxDateTime = new DateTime($maxDate); $minDateTime <= $maxDateTime;  $minDateTime->add(new DateInterval('P01D'))) {

So that a new DateTime object is not created on each iteration.

vascowhite
  • 18,120
  • 9
  • 61
  • 77
  • This was the problem thanks :). I thought that I have problem with some instantiation or more complex thing like this, but after the modification the loop ran correctly. – zsidanyi Sep 04 '13 at 08:47