1.2.1347. Use Positive Condition

Whenever possible, use a positive condition.

Positive conditions are easier to understand, and lead to less understanding problems. Negative conditions are not reported when else is not present.

<?php

// This is a positive condition
if ($a == 'b') {
    doSomething();
} else {
    doSomethingElse();
}

if (!empty($a)) {
    doSomething();
} else {
    doSomethingElse();
}

// This is a negative condition
if ($a == 'b') {
    doSomethingElse();
} else {
    doSomething();
}

// No need to force $a == 'b' with empty else
if ($a != 'b') {
    doSomethingElse();
}

?>

See also Double negatives should not not be avoided and How To Write Conditional Statements in PHP.

1.2.1347.1. Suggestions

  • Invert the code in the if branches, and the condition

1.2.1347.2. Specs

Short name

Structures/UsePositiveCondition

Rulesets

All, Analyze, Changed Behavior

Exakat since

0.8.6

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Examples

SPIP, ExpressionEngine

Available in

Entreprise Edition, Exakat Cloud