Skip to content

InvertedIfElseConstructs ​

info off by default quick-fix

Group: Control flow · PhpStorm name: InvertedIfElseConstructsInspection

An if/else whose condition is a negation (!expr, or false === expr) reads backwards: swapping the two branches and dropping the negation makes the main path positive and easier to follow.

Example ​

php
<?php
function ready(): bool { return true; }
function maybe(): ?bool { return null; }

if (!ready()) { wait(); }
else { go(); }

if ( ! ($left === $right) ) { differ(); }
else { same(); }

if ($mode === 1) { one(); }
elseif (!isset($cfg['x'])) { fallback(); }
else { useCfg(); }

if (FALSE === ready()) { wait(); }
else { go(); }

if (false === maybe()) { a(); } else { b(); }
if (!empty($list)) { a(); } else { b(); }
if ((!ready())) { a(); } else { b(); }
if (!ready()) { a(); } else b();
if (!ready()) a(); else { b(); }
if (!$p || !$q) { a(); } else { b(); }
if (!ready()) { a(); }
php
<?php
function ready(): bool { return true; }
function maybe(): ?bool { return null; }

if (ready()) { go(); }
else { wait(); }

if ($left === $right) { same(); }
else { differ(); }

if ($mode === 1) { one(); }
elseif (isset($cfg['x'])) { useCfg(); }
else { fallback(); }

if (ready()) { go(); }
else { wait(); }

if (false === maybe()) { a(); } else { b(); }
if (!empty($list)) { a(); } else { b(); }
if ((!ready())) { a(); } else { b(); }
if (!ready()) { a(); } else b();
if (!ready()) a(); else { b(); }
if (!$p || !$q) { a(); } else { b(); }
if (!ready()) { a(); }

Reported:

  • line 6: Negated condition with an else branch; swap the branches and drop the negation.
  • line 9: Negated condition with an else branch; swap the branches and drop the negation.
  • line 13: Negated condition with an else branch; swap the branches and drop the negation.
  • line 16: Negated condition with an else branch; swap the branches and drop the negation.

Configure ​

In custos.json:

json
{
  "rules": {
    "InvertedIfElseConstructs": {
      "enabled": true
    }
  }
}

Suppress ​

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

php
// @custos-ignore InvertedIfElseConstructs

/**
 * @noinspection InvertedIfElseConstructsInspection
 */

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