1.2.402. Else If Versus Elseif

Always use elseif instead of else and if.

The keyword elseif SHOULD be used instead of else if so that all control keywords look like single words”. Quoted from the PHP-FIG documentation

<?php

// Using elseif
if ($a == 1) { doSomething(); }
elseif ($a == 2) { doSomethingElseIf(); }
else { doSomethingElse(); }

// Using else if
if ($a == 1) { doSomething(); }
else if ($a == 2) { doSomethingElseIf(); }
else { doSomethingElse(); }

// Using else if, no {}
if ($a == 1)  doSomething();
else if ($a == 2) doSomethingElseIf();
else  doSomethingElse();

?>

See also elseif/else if.

1.2.402.1. Suggestions

  • Merge else and if into elseif

  • Turn the else expression into a block, and have more than the second if in this block

  • Turn the if / else if / else into a switch structure

1.2.402.2. Specs

Short name

Structures/ElseIfElseif

Rulesets

All, Analyze, CE, CI-checks, Rector, php-cs-fixable

Exakat since

0.8.4

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Features

if-then

Examples

TeamPass, Phpdocumentor

Available in

Entreprise Edition, Community Edition, Exakat Cloud