I’m refactoring some PHP code and discovered that certain nested combinations of
if () :
and
if () {
generate syntax errors. Not that I would normally mix the two, but I like to do frequent syntax checks as I’m writing code and I kept getting a syntax error because of this.
Example – generates syntax error:
if ( $test == 1 ) : if ( $test2 == 'a' ) { if ( $test3 == 'A' ) { } else { } } else : echo 'test2'; endif;
Example – does NOT generate syntax error:
if ( $test == 1 ) : if ( $test2 == 'a' ) : if ( $test3 == 'A' ) : else : endif; endif; else : echo 'test2'; endif;
Could someone please explain to me why the first block of code is generating an error?
This is a wild guess since I am not familiar with the grammar of PHP. But here goes:
The problem is the second
else. The parser can’t see if thiselseis belonging to the first or the second if (counting from the beginning). In your second example there is anendifmaking the secondif-block be terminated so there it can do the parse. Perhaps this is the famous ‘dangling-else’ problem in disguise?