Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, does elseif need a final else statement?

Is it ok to leave out the final else statement in an elseif block in PHP. Is this code OK

if ( condition ):
   // code
elseif ( othercondition ):
   // more code
endif;

or should it have else at the end ?

if ( condition ):
   // code
elseif ( othercondition ):
   // more code
else
   // more code
endif;

I'm sure it must be but I cant get it confirmed anywhere. Edit - I've tried it and it works but I just want to be sure.

like image 232
byronyasgur Avatar asked Aug 02 '12 21:08

byronyasgur


2 Answers

if you don't need a final else-block, don't write one. it's just senseless to have a block of code (possibly containing just a this is useless-comment) that isn't needed.

like image 169
oezi Avatar answered Sep 28 '22 07:09

oezi


While @oezi's answer is 100% correct, I would also add that with respect to best practice, the else condition should be used in all cases. This does not mean you have to use an else block literally, though, since you can accomplish the same thing logically by putting your "else code" before the if. For example:

$foo = 'baz';

if (...) {
    $foo = 'foo';
} else if (...) {
    $foo = 'bar';
}

...is functionally equivalent to:

if (...) {
    $foo = 'foo';
} else if (...) {
    $foo = 'bar';
} else {
    $foo = 'baz';
}

I would argue that the use of else is more clear when reading the code, but either way is okay. Just remember that leaving out the third case altogether is a common cause of bugs (and in some cases, even security holes).

like image 42
FtDRbwLXw6 Avatar answered Sep 28 '22 07:09

FtDRbwLXw6