1.2.1191. 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.1191.1. Connex PHP features¶
1.2.1191.1.1. Suggestions¶
Use parenthesis
Avoid ternaries and coalesce operators inside a string
1.2.1191.1.2. Specs¶
Short name |
Structures/TernaryInConcat |
Rulesets |
|
Exakat since |
0.8.4 |
PHP Version |
All |
Severity |
Critical |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
Examples |
|
Available in |