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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With