开发者

PHP nested if syntax error

I have a weird syntax issue relating to nested if statements.

This code errors:

if(true):
    if(true){
        var_dump(true);
    }
else:
    var_dump(false);
endif;

This code does not error (note the added ;):

if(true):
    if(true){
 开发者_如何学Go       var_dump(true);
    };
else:
    var_dump(false);
endif;

What gives?


It's because the else is assigned to the inner if without the ;


Note:

Mixing syntaxes in the same control block is not supported.

This is from the notes in the PHP manual:

http://php.net/manual/en/control-structures.alternative-syntax.php


I know this is an old question, but I found a valid answer to it. I changed the OP's code:

if(true):
   if(true){
       var_dump(true);
   }
else:
   var_dump(false);
endif;

to the following:

if (true) :
    {
        if (true) {
            var_dump ( true );
        } else {
            var_dump ( false );
        }
    }
endif;

which successfully ran and printed true.

The only change I made was that I wrapped the nested if in a block.

Simplified code:

if (true) :
    {
        if (true)
            var_dump ( true );
        else
            var_dump ( false );
    }
endif;

Note that I am using PHP 7.0.0.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜