1.2.819. No Need For Else

Else is not needed when the Then ends with a break. A break may be the following keywords : break, continue, return, goto. Any of these send the execution somewhere in the code. The else block is then executed as the main sequence, only if the condition fails.

<?php

function foo() {
    // Else may be in the main sequence.
    if ($a1) {
        return $a1;
    } else {
        $a++;
    }

    // Same as above, but negate the condition : if (!$a2) { return $a2; }
    if ($a2) {
        $a++;
    } else {
        return $a2;
    }

    // This is OK
    if ($a3) {
        return;
    }

    // This has no break
    if ($a4) {
        $a++;
    } else {
        $b++;
    }

    // This has no else
    if ($a5) {
        $a++;
    }
}
?>

See also Object Calisthenics, rule # 2.

1.2.819.1. Connex PHP features

1.2.819.1.1. Suggestions

  • Remove else block, but keep the code

1.2.819.1.2. Specs

Short name

Structures/NoNeedForElse

Rulesets

All, Analyze, Changed Behavior

Exakat since

0.10.4

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Examples

Thelia, ThinkPHP

Available in

Entreprise Edition, Exakat Cloud