Operator precedence is the issue as to when parenthesis are necessary (notwithstanding readability).
When dealing with the ternary operator look at the order PHP uses to group expressions, start with the ternary operator(s) and examine the operators that are grouped after the ternary operator. Those are the operators that have the potential to produce erroneous output.
PHP Operator Precedence, starting with ternary:
Assoc. Operators Additional Information
...
left ? : ternary
right = += -= *= **= /= .= %=
&= %= &= |= ^= <<= >>= => assignment
left and logical
left xor logical
left or logical
left , many uses
In this case there are the assignment operators, the lower precedence logical operators, and comma.
It appears the ternary and assignment are equal, therefore grouping is determined by their associativity when the two are in the same statement.
$a = true? 'yes': 'no';
// $a is assigned 'yes'
Assignment is right associative so, in relation to the =
, expressions are grouped right to left. In this case the ternary comes first (rightmost) and the statement works as expected.
That leaves the lower precedence boolean and the comma.
echo true and true? 'yes': 'no';
// Echos: 1
// Grouped like: echo true and (true? 'yes': 'no');
Not as expected. Use parenthesis to force intended grouping:
echo (true and true)? 'yes': 'no';
// Echos: yes
When using higher precedence boolean operators, which are grouped before the ternary operator, parenthesis are not necessary.
echo true && true? 'yes': 'no';
// Echos: yes
Bottom line, when operator precedence is unclear, or readability is desired, use parenthesis.