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.
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.
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).
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