Skip to content

SenselessTernaryOperator ​

warning on by default quick-fix

Group: Confusing constructs · PhpStorm name: SenselessTernaryOperatorInspection

$a === $b ? $a : $b always evaluates to $b: when the two are identical it does not matter which one is returned. The same holds for !== with swapped branches. Such ternaries only add branching; replace them with the operand that is always the result.

Example ​

php
<?php
$a = $left === $right ? $left : $right;
$b = $left !== $right ? $left : $right;
$c = $size === -1 ? -1 : $size;
$d = ($ref === null) ? $ref : null;
$e = $t !== 'n/a' ? $t : 'n/a';
$f = f($ratio !== 1.5 ? 1.5 : $ratio);
$g = $left == $right ? $left : $right;
$h = $left === $right ?: $right;
$i = $left === $right ? ($left) : $right;
$j = $left === $right ? $left : $other;
php
<?php
$a = $right;
$b = $left;
$c = $size;
$d = null;
$e = $t;
$f = f(1.5);
$g = $left == $right ? $left : $right;
$h = $left === $right ?: $right;
$i = $left === $right ? ($left) : $right;
$j = $left === $right ? $left : $other;

Reported:

  • line 2: This ternary always yields '$right'; use it directly.
  • line 3: This ternary always yields '$left'; use it directly.
  • line 4: This ternary always yields '$size'; use it directly.
  • line 5: This ternary always yields 'null'; use it directly.
  • line 6: This ternary always yields '$t'; use it directly.
  • line 7: This ternary always yields '1.5'; use it directly.

Configure ​

In custos.json:

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

Suppress ​

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

php
// @custos-ignore SenselessTernaryOperator

/**
 * @noinspection SenselessTernaryOperatorInspection
 */

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