Skip to content

ElvisOperatorCanBeUsed ​

info on by default quick-fix

Group: Language level migration · PhpStorm name: ElvisOperatorCanBeUsedInspection

A full ternary whose "then" branch repeats its condition ($a ? $a : $b) can be written with the short ternary operator $a ?: $b (PHP 5.3+), which is shorter and evaluates the condition once.

Example ​

php
<?php
$label  = $name ? $name : 'guest';
$limit  = $cfg['max'] ? ( $cfg['max'] ) : 10;
$owner  = (($user)) ? $user : $fallback;
$title  = $page->title ? $page->title : (DEFAULT_TITLE);

$keep1  = $name ?: 'guest';
$keep2  = $name ? 'guest' : $name;
$keep3  = !$name ? $name : 'guest';
$keep4  = isset($name) ? $name : 'guest';
$keep5  = getTitle() ? getTitle() : DEFAULT_TITLE;
php
<?php
$label  = $name ?: 'guest';
$limit  = $cfg['max'] ?: 10;
$owner  = (($user)) ?: $fallback;
$title  = $page->title ?: (DEFAULT_TITLE);

$keep1  = $name ?: 'guest';
$keep2  = $name ? 'guest' : $name;
$keep3  = !$name ? $name : 'guest';
$keep4  = isset($name) ? $name : 'guest';
$keep5  = getTitle() ? getTitle() : DEFAULT_TITLE;

Reported:

  • line 2: Use the short ternary: '$name ?: 'guest''.
  • line 3: Use the short ternary: '$cfg['max'] ?: 10'.
  • line 4: Use the short ternary: '(($user)) ?: $fallback'.
  • line 5: Use the short ternary: '$page->title ?: (DEFAULT_TITLE)'.

Configure ​

In custos.json:

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

Suppress ​

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

php
// @custos-ignore ElvisOperatorCanBeUsed

/**
 * @noinspection ElvisOperatorCanBeUsedInspection
 */

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