1

For example in the following statement,

$class = (  is_array($tagClasses) ? 'class="'.implode(" ",$tagClasses).'"' : ''  );

is the outermost parentheses only for readability or does it really have any other purpose?

I think it is for readability and code-aesthetics only, unless you have other things happening in the same statement, in which you have to separate out this part of the statement and dictate what is executed first.

But I have never seen a statement like that without an enclosing parenthesis, and have been thinking about this for quite some time. Therefore this question.

Solace
  • 8,612
  • 22
  • 95
  • 183
  • 1
    it's for readability. – Alive to die - Anant May 22 '15 at 07:45
  • Possible duplicate of http://stackoverflow.com/questions/26389123/are-parentheses-required-in-psr-2-php-ternary-syntax – Rikesh May 22 '15 at 07:46
  • 1
    I've had occasional problems where PHP has misinterpreted the order of execution with a ternary statement, particularly when concatenating the result into an output string. I routinely wrap ternary expressions in parentheses to avoid that problem. –  May 22 '15 at 07:49
  • @HoboSapiens I have also experienced that in more complex statements. – Solace May 22 '15 at 08:16
  • @Rikesh My search had missed that. Thanks for pointing out though. – Solace May 22 '15 at 08:20

1 Answers1

2

The original intent was readability I guess or maybe the developer was just following a Coding Standard. Though wrapping and indenting would help on readability way more than adding unnecessary parenthesis. Like this for exmaple:

$class = is_array($tagClasses)
    ? 'class="' . implode(" ", $tagClasses) . '"'
    : '';

When you definitely want to add () around a ternary operator is when you are nesting one to another (which is not nice anyway), or you can put the operands of the operator between () for the sake of readability if you have complex expressions there.

emul
  • 110
  • 9