1.2.1183. Ternary In Concat

Ternary and coalesce operator have higher priority than dot ‘.’ for concatenation. This means that :

prints actually 'E', instead of the awaited 'B0CE'.

To be safe, always add parenthesis when using ternary operator with concatenation.

<?php
  // print B0CE as expected
  print 'B'.$b.'C'. ($b > 1 ? 'D') : 'E';

  // print E, instead of B0CE
  print 'B'.$b.'C'. $b > 1 ? 'D' : 'E';

  print 'B'.$b.'C'. $b > 1 ? 'D' : 'E';
?>

See also Operator Precedence.

1.2.1183.1. Suggestions

  • Use parenthesis

  • Avoid ternaries and coalesce operators inside a string

1.2.1183.2. Specs

Short name

Structures/TernaryInConcat

Rulesets

All, Analyze, CE, CI-checks

Exakat since

0.8.4

PHP Version

All

Severity

Critical

Time To Fix

Quick (30 mins)

Precision

Very high

Features

ternary, concatenation

Examples

TeamPass

Available in

Entreprise Edition, Community Edition, Exakat Cloud