Mazatec
Mazatec

Reputation: 11649

PHP: Can you put a DateTime object in a while loop?

I saw this code on a forum:

 $begin = new DateTime( $start_date );
    $end = new DateTime(date("Y-m-d",strtotime("+1 day", strtotime($end_date))));
    while($begin < $end) {
        $period[] = $begin->format('Y-m-d');
        $begin->modify('+1 day');
    }

I want to do exactly what the OP was asking i.e. create a date interval of 1 day without using DateInterval class as I am not using PHP 5.3 (I'm using 5.2)

However when I try to use the $period array I get an error:

Undefined variable: period

This is my code:

    $start = new DateTime("09-09-2011");
    $end   = new DateTime("24-09-2011");

         while($start < $end) {

        $period[] = $start->format('Y-m-d');
        $start->modify('+1 day');

        }

print_r($period) //error - undefined variable

Why does it not work - is it to do with putting a datetime object in a while loop?

Upvotes: 2

Views: 3176

Answers (3)

GordonM
GordonM

Reputation: 31730

You can't compare DateTime objects directly unless you're using PHP 5.2.2 or newer. If you're using an older version then your while condition will never evaluate to true and your loop will never run. As a result, your period array will never be created.

You'll probably have to extract the values of the dates from the datetime objects and compare them some other way.

Failing that, you could upgrade to a newer version of PHP.

Upvotes: 0

George Cummins
George Cummins

Reputation: 28906

$period is defined in your while() loop. If the loop never runs (ie, if $start < $end never evaluates to true) the variable is never defined.

You can correct this by explicitly defining the variable before the while() loop:

$period = array();
while($start < $end) {
    ...

Upvotes: 1

genesis
genesis

Reputation: 50976

so define it easily

$period = array();

however, this will never go to that while loop = this code is not useful

Upvotes: 1

Related Questions