Bill
Bill

Reputation: 4413

Mixed syntax for control structures generating syntax errors

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?

Upvotes: 0

Views: 380

Answers (5)

Allain Lalonde
Allain Lalonde

Reputation: 93318

Indentation be damned, it's interpreting the first example as being an if using braces matched up with an else using the alternate syntax.

Consistency is the rule of thumb here and the interpretation is ambiguous to any reader anyway, so either put in the semicolon as suggested in the other answers, or better yet... clean up the code. That's horrible!

Upvotes: 1

dmazzoni
dmazzoni

Reputation: 13236

It works fine if you put a semicolon after the last curly-brace:

if ( $test == 1 ) :
  if ( $test2 == 'a' ) {
    if ( $test3 == 'A' ) {
    } else {
    }
  };
else :
  echo 'test2';
endif;

Upvotes: 1

Alex Weinstein
Alex Weinstein

Reputation: 9891

The only thing I can say here is that the code is completely unreadable. Avoid : like plague. Use familiar, C-style curly brace syntax.

The quality of the code is very much driven by its readability, so do make an effort to clean this up, you'll save yourself a bunch of surprising bugs.

Upvotes: 0

Owen
Owen

Reputation: 84493

i don't know the exact reason why. here's a related PHP bug post in which a dev basically says, "just don't do it" :). i haven't poured through the PHP source code lately, but if i had to hazard a guess, it's due to not checking for alternative syntax while recursively going through if statements.

Upvotes: 2

I GIVE CRAP ANSWERS
I GIVE CRAP ANSWERS

Reputation: 18849

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 this else is belonging to the first or the second if (counting from the beginning). In your second example there is an endif making the second if-block be terminated so there it can do the parse. Perhaps this is the famous 'dangling-else' problem in disguise?

Upvotes: 2

Related Questions