Skip to content

TernaryOperatorSimplify ​

info on by default quick-fix

Group: Control flow · PhpStorm name: TernaryOperatorSimplifyInspection

A ternary whose branches are the literals true and false merely restates its condition. When the condition is a binary expression, the ternary can be replaced by the condition itself, its negation, or a boolean cast.

Example ​

php
<?php
function probe($n, $m, $a, $b, $obj, int $k) {
    $r = $n !== 7 ? true : false;
    $r = $n <= 7 ? false : true;
    $r = $k <= 7 ? false : true;
    $r = $m % 2 ? TRUE : FALSE;
    $r = $m | 4 ? false : true;
    $r = $a || $b ? true : false;
    $r = $a || $b ? false : true;
    $r = $obj instanceof Countable ? true : false;
    $r = ($n == $m) ? (true) : (false);
    $r = $n == $m ? true : 0;
    $r = in_array($n, $b) ? false : true;
    $r = $n ?: false;
    return $r;
}
php
<?php
function probe($n, $m, $a, $b, $obj, int $k) {
    $r = $n !== 7;
    $r = !($n <= 7);
    $r = $k > 7;
    $r = (bool)($m % 2);
    $r = !($m | 4);
    $r = ($a || $b);
    $r = !($a || $b);
    $r = (bool)($obj instanceof Countable);
    $r = $n == $m;
    $r = $n == $m ? true : 0;
    $r = in_array($n, $b) ? false : true;
    $r = $n ?: false;
    return $r;
}

Reported:

  • line 3: Replace the ternary with '$n !== 7'.
  • line 4: Replace the ternary with '!($n <= 7)'.
  • line 5: Replace the ternary with '$k > 7'.
  • line 6: Replace the ternary with '(bool)($m % 2)'.
  • line 7: Replace the ternary with '!($m | 4)'.
  • line 8: Replace the ternary with '($a || $b)'.
  • line 9: Replace the ternary with '!($a || $b)'.
  • line 10: Replace the ternary with '(bool)($obj instanceof Countable)'.
  • line 11: Replace the ternary with '$n == $m'.

Configure ​

In custos.json:

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

Suppress ​

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

php
// @custos-ignore TernaryOperatorSimplify

/**
 * @noinspection TernaryOperatorSimplifyInspection
 */

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