PHP 8.3.0 RC 6 available for testing

else

(PHP 4, PHP 5, PHP 7, PHP 8)

经常需要在满足某个条件时执行一条语句,而在不满足该条件时执行其它语句,这正是 else 的功能。else 延伸了 if 语句,可以在 if 语句中的表达式的值为 false 时执行语句。例如以下代码在 $a 大于 $b 时显示 a is bigger than b,反之则显示 a is NOT bigger than b

<?php
if ($a > $b) {
echo
"a is greater than b";
} else {
echo
"a is NOT greater than b";
}
?>
else 语句仅在 if 以及 elseif(如果有的话)语句中的表达式的值为 false 时执行(参见 elseif)。

注意: 悬挂的 else

在多层嵌套 if-else 语句的情况下, else 总是与最近的 if 进行关联。

<?php
$a
= false;
$b = true;
if (
$a)
if (
$b)
echo
"b";
else
echo
"c";
?>
虽然存在缩进(对 PHP 来说,无关紧要), 但是 else 还是与 if ($b) 进行关联,所以以上示例不会产生任何输出。虽然可以依赖此特性,但是推荐使用花括号,避免潜在的歧义问题。

add a note

User Contributed Notes 10 notes

up
23
dormeydo at gmail dot com
15 years ago
An alternative and very useful syntax is the following one:

statement ? execute if true : execute if false

Ths is very usefull for dynamic outout inside strings, for example:

print('$a is ' . ($a > $b ? 'bigger than' : ($a == $b ? 'equal to' : 'smaler than' )) . ' $b');

This will print "$a is smaler than $b" is $b is bigger than $a, "$a is bigger than $b" if $a si bigger and "$a is equal to $b" if they are same.
up
11
Caliban Darklock
19 years ago
If you're coming from another language that does not have the "elseif" construct (e.g. C++), it's important to recognise that "else if" is a nested language construct and "elseif" is a linear language construct; they may be compared in performance to a recursive loop as opposed to an iterative loop.

<?php
$limit
=1000;
for(
$idx=0;$idx<$limit;$idx++)
{
$list[]="if(false) echo \"$idx;\n\"; else"; }
$list[]=" echo \"$idx\n\";";
$space=implode(" ",$list);| // if ... else if ... else
$nospace=implode("",$list); // if ... elseif ... else
$start=array_sum(explode(" ",microtime()));
eval(
$space);
$end=array_sum(explode(" ",microtime()));
echo
$end-$start . " seconds\n";
$start=array_sum(explode(" ",microtime()));
eval(
$nospace);
$end=array_sum(explode(" ",microtime()));
echo
$end-$start . " seconds\n";
?>

This test should show that "elseif" executes in roughly two-thirds the time of "else if". (Increasing $limit will also eventually cause a parser stack overflow error, but the level where this happens is ridiculous in real world terms. Nobody normally nests if() blocks to more than a thousand levels unless they're trying to break things, which is a whole different problem.)

There is still a need for "else if", as you may have additional code to be executed unconditionally at some rung of the ladder; an "else if" construction allows this unconditional code to be elegantly inserted before or after the entire rest of the process. Consider the following elseif() ladder:

<?php
if($a) { conditional1(); }
elseif(
$b) { conditional2(); }
elseif(
$c) { conditional3(); }
elseif(
$d) { conditional4(); }
elseif(
$e) { conditional5(); }
elseif(
$f) { conditional6(); }
elseif(
$g) { conditional7(); }
elseif(
$h) { conditional8(); }
else {
conditional9(); }
?>

To insert unconditional preprocessing code for $e onward, one need only split the "elseif":

<?php
if($a) { conditional1(); }
elseif(
$b) { conditional2(); }
elseif(
$c) { conditional3(); }
elseif(
$d) { conditional4(); }
else {
....
unconditional();
....if(
$e) { conditional5(); }
....elseif(
$f) { conditional6(); }
....elseif(
$g) { conditional7(); }
....elseif(
$h) { conditional8(); }
....else {
conditional9(); }
}
?>

The alternative is to duplicate the unconditional code throughout the construct.
up
0
mparsa1372 at gmail dot com
2 years ago
//Output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good night!":

<?php
$t
= date("H");

if (
$t < "10") {
echo
"Have a good morning!";
} elseif (
$t < "20") {
echo
"Have a good day!";
} else {
echo
"Have a good night!";
}
?>
up
0
emmanuel dot orchanian at hotmail dot fr
3 years ago
// You can remplace this :
if (...) {
return 111 ;
} else {
return 222 ;
}

// By this :
if (...) {
return 111 ;
}
return 222 ;
up
-1
mparsa1372 at gmail dot com
2 years ago
//Output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:

<?php
$t
= date("H");

if (
$t < "20") {
echo
"Have a good day!";
} else {
echo
"Have a good night!";
}
?>
up
-1
mitch at mitchellbeaumont dot com
16 years ago
At gwmpro at yahoo dot com

The curly brace is not required however, for readability and maintenance, many developers would consider it bad style not to include them.
up
-2
zithronospam at remove dot gmail dot com at
7 years ago
Alternate syntax is great (dont remove it!), but take care using "else:" after one liners, this wont work:
<?php
if (true):
if (
true) print('This results in a parse error (unexpected ":" on line <the_else_line>)');
else:
if (
true) { print('Replacing above line with this one also triggers a parse error, curly braces do not help in this case') }
endif;
?>

Either use the alternate syntax on the line in error: <?php if(true):print('This works as its ended by an');endif; ?>
Or write some more code on a newline between the one-liner and the following else (eg. "$var=1;" is enough, even a single semi-colon is, but read below).

A third way is to add a semi-colon to the one-liner, having two if necessary:
<?php
if (true):
if (
true) print('This is valid again');;
else:
// ...
endif;

// It works with the curly braces form too:
if (true):
if (
true) { print('This get displayed, even if the doc says the opposite about mixing syntaxes') };
else:
// ...
endif;
?>
I can only guess that the added semi-colon makes it work by "closing the if" in a way.
Subsequent semi-colons don't matter, and the semi-colon can be anywhere: at the end of the line, on the following line on its own, or just before the else like ";else". But who would do that anyway.

TL;DR/conclusion:
- avoid mixing alternate syntax and one liners in if/else control structures
- avoid mixing syntaxes inside the blocks (even if it works using this semi-colon trick).

================================
Note to editors: the behaviour described is specifically linked to the use of an else, but this note could also be added to the more general "Alternative syntax for control structures" page as it's also commenting on mixing syntaxes. You know better!
up
-11
php at keith tyler dot com
12 years ago
This is valid syntax:

<?php
if ($a) print "a is true";
else print
"a is false";
?>

A holdover from the bash-style compatibility in older PHP versions, perhaps.
up
-18
Larry H-C
14 years ago
When you escape out of HTML, you can get an UNEXPECTED T_ELSE error with the following:

Error:

<? if( $condition ) {
dosomething;
}
?>

<? else {
dosomethingelse;
}
?>

Correct:

<? if( $condition ) {
dosomething;
?>

<? } else {
dosomethingelse;
}
?>

Apparently the compiler thinks a ?> <? breaks the connection between the } and the else
up
-29
Theoden
15 years ago
At Caliban Darklock

I don't know if it is just improvements in the parser, but there is a negligible difference in the performance of "elseif" vs "else if" as of version 5. One thousandth of a second in your example and 8 thousandths if the eval statement is repeated 5 times.
If the constructs are in regular code, then there appears to be no difference. This leads me to believe that the difference in the eval code is from there being an extra parser token.

Also the main performance burden of recursive functions is the stack operations of changing the context. In this case I believe that it would parse to very similar (if not identical) jmp controls.

In summary, use your preference. Readability and maintainability rank far higher on the priority scale.

One Additional note, there appears to be a limit of the number of "else if" statements (perhaps nested statements in general) that php will handle before starting to get screwy. This limit is about 1100. "elseif" is not affected by this.
To Top