Posted by: phillipnb | January 29, 2011

Misuse of Ternary Operator


Happy New Year – Recently while I was debugging one of our team member’s code,I came across a grave misuse of the ternary operator. The code that I am talking about is shown below:

echo $comments ? $comments : $comments;

The explanation given by the developer for this kind of usage of the ternary operator was “if $comments has a value then it will print that,if not, it will print an empty string”.

The operator that is used here is called the ternary operator(:?:.) and the definition given in the php manual for a ternary operator is “It should be used to select between two expressions depending on a third one, rather than to select two sentences or paths of execution”. Honestly, the above php code is a misuse of ternary operator.

Regarding this kind of usage of the ternary operator – all I can say is that this type of usuage of the ternary operator not only makes the code complicated to debug but also misleads even a well experienced php developer. As the definition says, it should be used to select between two expressions rather than switch between the same variable based on its content. The same thing that is written above can be achieved by a simple if-else statement. for e.g.

if (!empty($comments))
{
  echo $comments;
}
else
{
 $blank = '$comments is empty';
 echo $blank;
}

So, next time when you use a ternary operator make sure you really understand what it is used for and make a wise decision as to whether to use it or not. Never use the ternary operator just for the sake of using it.

Till Next Time
Happy PHPing

Advertisements

Responses

  1. echo $comments ? $comments : $comments;

    Isn’t it equal to “echo $comments;” ?

  2. Yes, you are right. The point that I am trying to make is that, something that can be achieved using echo $comments; does not require the use of ternary operator.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: