6

Few days ago I stopped on some PHP's developers quide (for contributors to particular project) and it stated, that elseif must be strictly used instead of else if -- without giving any reason, why?

Can someone clarify this? I don't see neither much difference nor any argument supporting this.

Info: I believe, there are more languages, than just PHP, that this problem strikes, that's why I asked here, not on Stack Overflow. Feel free to migrate, if necessary.

  • 1
    This is answered in SO – Srihari May 30 '14 at 11:18
11

The behavior when using curly brackets is exactly the same. However when not using curly brackets but colon instead, the following will not compile:

if($a > $b):
    echo $a." is greater than ".$b;
else if($a == $b): // Will not compile.
    echo "The above line causes a parse error.";
endif;

I assume that the reason for preferring elseif over else if is either to be able to switch to and from curly brackets without creating a compile error or, probably more likely, it is a stylistic choice and prefers that only elseif is used.

According to the php documentation:

Nota: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.

7

Besides this answer, in both PSR2.0 and PEAR coding standards the use of elseif instead of else if is specified so that all control keywords look like single words:

<?php 
if ($expr1) {
    // if body 
} elseif ($expr2) {
    // elseif body 
} else {
    // else body; 
}

The keyword elseif SHOULD be used instead of else if so that all control keywords look like single words

Source: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md#51-if-elseif-else

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.