开发者

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 DateTim开发者_JS百科e("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?


so define it easily

$period = array();

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


$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) {
    ...


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜