Skip to content

RedundantElseClause ​

warning on by default quick-fix

Group: Control flow · PhpStorm name: RedundantElseClauseInspection

When an if body always leaves the current flow (return, throw, break, continue, exit/die), the following else/elseif keyword is superfluous: its code can simply follow the if. Removing it flattens nesting.

Example ​

php
<?php
function route($req, $list) {
    if ($req === null) { exit(3); } else { ; }
    if (!$list) { throw new LogicException('none'); }
    else { ; }
    foreach ($list as $item) {
        if ($item < 0) { continue; } else if ($item > 9) { break; }
    }
    if ($req === 'a') { return 1; }
    elseif ($req === 'b') { $list = []; } else { $list = [1]; }
    if ($req === 'c') { $list[] = 2; } else { ; }
    if ($req === 'd') return 4; else ;
    if ($req === 'e') { return 5; } else $list = [];
    if ($req === 'f') { ; } else if ($req === 'g') { return 6; } else { ; }
    if ($req === 'h'):
        return 7;
    else:
        $list = null;
    endif;
    return $list;
}
php
<?php
function route($req, $list) {
    if ($req === null) { exit(3); };
    if (!$list) { throw new LogicException('none'); };
    foreach ($list as $item) {
        if ($item < 0) { continue; }
        if ($item > 9) { break; }
    }
    if ($req === 'a') { return 1; }
    if ($req === 'b') { $list = []; } else { $list = [1]; }
    if ($req === 'c') { $list[] = 2; } else { ; }
    if ($req === 'd') return 4; else ;
    if ($req === 'e') { return 5; } else $list = [];
    if ($req === 'f') { ; } else if ($req === 'g') { return 6; } else { ; }
    if ($req === 'h'):
        return 7;
    else:
        $list = null;
    endif;
    return $list;
}

Reported:

  • line 3: Drop the 'else' and move its code after the 'if'.
  • line 5: Drop the 'else' and move its code after the 'if'.
  • line 7: Drop the 'else' and move its code after the 'if'.
  • line 10: Turn this 'elseif' into a separate 'if'.

Configure ​

In custos.json:

json
{
  "rules": {
    "RedundantElseClause": {
      "enabled": false
    }
  }
}

Suppress ​

Before the statement or declaration (or the first statement of the file), either of:

php
// @custos-ignore RedundantElseClause

/**
 * @noinspection RedundantElseClauseInspection
 */

Released under the MIT License. Rule catalogue modelled on Php Inspections (EA Extended); independent clean-room implementation.