PHP3 Manual | ||
---|---|---|
Prev | Chapter 6. Language constructs | Next |
ELSEIF, as its name suggests, is a combination of IF and ELSE. Like ELSE, it extends an IF statement to execute a different statement in case the original IF expression evaluates to FALSE. However, unlike ELSE, it will execute that alternative expression only if the ELSEIF expression evaluates to TRUE. For example, the following code would display 'a is bigger than b' if $a>$b, 'a is equal to b' if $a==$b, and 'a is smaller than b' if $a<$b:
if ($a > $b) { print "a is bigger than b"; } elseif ($a == $b) { print "a is equal to b"; } else { print "a is smaller than b"; }
There may be several ELSEIFs within the same IF statement. The first ELSEIF expression (if any) that evaluates to TRUE would be executed. In PHP 3, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior.
The ELSEIF statement is only executed if the IF expression and any previous ELSEIF expressions evaluated to FALSE, and the current ELSEIF expression evaluated to TRUE.
PHP 3 offers a different way to group statements within an IF statement. This is most commonly used when you nest HTML blocks inside IF statements, but can be used anywhere. Instead of using curly braces, the IF(expr) should be followed by a colon, the list of one or more statements, and end with ENDIF;. Consider the following example:
<?php if ($a==5): ?> A = 5 <?php endif; ?>
In the above example, the HTML block "A = 5" is nested within an IF statement written in the alternative syntax. The HTML block would be displayed only if $a is equal to 5.
The alternative syntax applies to ELSE and ELSEIF (expr) as well. The following is an IF statement with ELSEIF and ELSE in the alternative format:
if ($a==5): print "a equals 5"; print "..."; elseif ($a==6): print "a equals 6"; print "!!!"; else: print "a is neither 5 nor 6"; endif;
Prev | Home | Next |
ELSE | Up | WHILE |