1.2.1114. Should Use Ternary Operator

Ternary operators are the best when assigning values to a variable.

They are less verbose, compatible with assignation and easier to read.

<?php
    // verbose if then structure
    if ($a == 3) {
        $b = 2;
    } else {
        $b = 3;
    }

    // compact ternary call
    $b = ($a == 3) ? 2 : 3;

    // verbose if then structure
    // Works with short assignations and simple expressions
    if ($a != 3) {
        $b += 2 - $a * 4;
    } else {
        $b += 3;
    }

    // compact ternary call
    $b += ($a != 3) ? 2 - $a * 4 : 3;

?>

See also Ternary Operator and Shorthand comparisons in PHP.

1.2.1114.1. Suggestions

  • Use the ternary operator

1.2.1114.2. Specs

Short name

Structures/ShouldMakeTernary

Rulesets

All, Analyze, CE, CI-checks

Exakat since

0.8.5

PHP Version

All

Severity

Minor

Time To Fix

Instant (5 mins)

Precision

Very high

Features

ternary

Examples

ChurchCRM

Available in

Entreprise Edition, Community Edition, Exakat Cloud