There is no good way to interpret the dangling else. One must pick a way and apply rules based on that.
Since there is no endif before an else, there is no easy way for PHP to know what you mean.
elseif
Wie der Name schon sagt ist elseif eine Verbindung von if und else. Wie else erweitert sie eine if-Anweisung um die Ausführung anderer Anweisungen, sobald die normale if-Bedingung als FALSE ausgewertet wird. Anders als bei else wird die Ausführung dieser alternativen Anweisungen nur durchgeführt, wenn die bei elseif angegebene alternative Bedingung als TRUE ausgewertet wird. Der folgende Code wird z.B. a ist größer als b, a ist gleich b oder a ist kleiner als b ausgeben:
<?php
if ($a > $b) {
echo "a ist größer als b";
} elseif ($a == $b) {
echo "a ist gleich b";
} else {
echo "a ist kleiner als b";
}
?>
Es kann mehrere elseif-Anweisungen innerhalb einer if-Anweisung geben. Die erste elseif-Bedingung (falls vorhanden), die TRUE ist, wird ausgeführt. In PHP kann man auch 'else if' schreiben (zwei Wörter). Das Verhalten ist identisch zu 'elseif' (ein Wort). Die Bedeutung der Syntax ist leicht unterschiedlich (falls Sie mit C vertraut sind, das ist das gleiche Verhalten) aber der Grundtenor ist der, dass beide Schreibweisen, bezogen auf das Ergebnis, sich exakt gleich verhalten.
Die elseif-Anweisung wird nur ausgeführt, wenn die vorausgehende if-Bedingung sowie jede vorherige elseif-Bedingung als FALSE ausgewertet wird und die aktuelle elseif-Bedingung TRUE ist.
elseif
27-Dec-2006 09:59
The parser doesn't handle mixing alternative if syntaxes as reasonably as possible.
The following is illegal (as it should be):
<?
if($a):
echo $a;
else {
echo $c;
}
?>
This is also illegal (as it should be):
<?
if($a) {
echo $a;
}
else:
echo $c;
endif;
?>
But since the two alternative if syntaxes are not interchangeable, it's reasonable to expect that the parser wouldn't try matching else statements using one style to if statement using the alternative style. In other words, one would expect that this would work:
<?
if($a):
echo $a;
if($b) {
echo $b;
}
else:
echo $c;
endif;
?>
Instead of concluding that the else statement was intended to match the if($b) statement (and erroring out), the parser could match the else statement to the if($a) statement, which shares its syntax.
While it's understandable that the PHP developers don't consider this a bug, or don't consider it a bug worth their time, jsimlo was right to point out that mixing alternative if syntaxes might lead to unexpected results.
