Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if {} in if: endif

Tags:

php

Why it won't work? Appears Parse error: syntax error, unexpected ':' ... on line 7

$a = 0; $b = 1; $c = 3; $d = 4;
if ($a == $b):
   if ($b == $c) {
       // something
   }
else:
   $c = $a;
endif;

But if i change it to (just added else statement):

$a = 0; $b = 1; $c = 3; $d = 4;
if ($a == $b):
   if ($b == $c) {
       // something
   } else {
       // something
   }
else:
   $c = $a;
endif;

It works fine.

Why is that? isn't it a PHP bug? Or there is a rule about if...else i should know?

Anyway, i'm using PHP 5.3.3 version.

like image 528
user1301744 Avatar asked Mar 29 '12 20:03

user1301744


2 Answers

I am not sure if I would call this is a bug, but I believe you're having this issue because of a dangling else, in conjunction with your mixed if-else syntax:

if ($a == $b):            // 1
    if ($b == $c) {       // 2 
        // something      // 3
    }                     // 4
else:                     // 5 - this else
    $c = $a;              // 6
endif;                    // 7

Note how the else on line 5 is ambiguous: it could "belong" either to the first or second if statements.

You can easily remove that ambiguity and fix your syntax error by adding a semicolon after your nested if:

if ($a == $b):            // 1
    if ($b == $c) {       // 2 
        // something      // 3
    };                    // 4 - here
else:                     // 5 
    $c = $a;              // 6
endif;                    // 7

On another note, please don't use this syntax unless you want your fellow programmers to bludgeon you to death in your sleep.

like image 101
NullUserException Avatar answered Nov 14 '22 05:11

NullUserException


As mentioned in comments on the PHP manual's control structure page the parser appears to not always assume that an if from one style should not be matched with an else using the other.

like image 28
Troubadour Avatar answered Nov 14 '22 06:11

Troubadour