1.2.639. Logical Mistakes

Avoid logical mistakes within long expressions.

Sometimes, the logic is not what it seems. It is important to check the actual impact of every part of the logical expression. Do not hesitate to make a table with all possible cases. If those cases are too numerous, it may be time to rethink the whole expression. Inspired by an article from Andrey Karpov.

<?php

// Always true
if ($a != 1 || $a != 2) { }

// $a == 1 is useless
if ($a == 1 || $a != 2) {}

// Always false
if ($a == 1 && $a == 2) {}

// $a != 2 is useless
if ($a == 1 && $a != 2) {}

?>

See also Logical Expressions in C/C++. Mistakes Made by Professionals.

1.2.639.1. Suggestions

  • Change the expressions for them to have a real meaning

1.2.639.2. Specs

Short name

Structures/LogicalMistakes

Rulesets

All, Analyze, CE, CI-checks

Exakat since

0.8.4

PHP Version

All

Severity

Critical

Time To Fix

Quick (30 mins)

Precision

High

Examples

Dolibarr, Cleverstyle

Available in

Entreprise Edition, Community Edition, Exakat Cloud