1.2.157. Coalesce And Ternary Operators Order

The ternary operator and the null-coalesce operator cannot be used in any order. The ternary operator is wider, so ot should be used last.

In particular, the ternary operator works on truthy values, and NULL is a falsy one. So, NULL might be captured by the ternary operator, and the following coalesce operator has no chance to process it.

On the other hand, the coalesce operator only process NULL, and will leave the false (or any other falsy value) to process to the ternary operator.

<?php

// Good order : NULL is processed first, otherwise, false will be processed.
$b = $a ?? 'B' ?: 'C';

// Wrong order : this will never use the ??
$b = $a ?: 'C' ?? 'B';

?>

1.2.157.1. Suggestions

  • Use the good order of operator : most specific first, then less specific.

1.2.157.2. Specs

Short name

Structures/CoalesceNullCoalesce

Rulesets

All, Analyze, Changed Behavior

Exakat since

2.5.0

PHP Version

With PHP 7.0 and more recent

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

High

Features

ternary, null, coalesce

Available in

Entreprise Edition, Exakat Cloud