2

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){
        var_dump(true);
    };
else:
    var_dump(false);
endif;

What gives?

9
  • 4
    the ; is expected after endif. also PLEASE @anybody dont use the if(): endif; syntax :P Commented Mar 31, 2011 at 21:46
  • 1
    Could be just my opinion, but I always viewed that syntax as a horrible horrible perl artifact. (+1 n00b). I'd like to add this is bad in while loops as well (damn popular in wordpress). Commented Mar 31, 2011 at 21:47
  • 3
    @n00b and @Christian Sciberras it is intended for PHP templating I believe and not for in methods etc. It is useful when you have PHP logic mixed with HTML as it is easier to read than a floating curly brace which could be to close an if or a while or for etc. php.net/manual/en/control-structures.alternative-syntax.php Commented Mar 31, 2011 at 21:52
  • 2
    @Christian Sciberras Yes, there are alternatives. I was just pointing out that jumping on it as not having a purpose is short sighted and not necessarily correct in every instance. Commented Mar 31, 2011 at 21:58
  • 2
    @Treffynnon - thank you for being the voice of reason. Commented Mar 31, 2011 at 22:16

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

3
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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.