Sunday, November 4th, 2007

Ternary Operator in PHP

Over on Planet PHP there's a running debate [see here, here & here] over the use of the ternary operator. I love a good debate so I thought I'd chip in with my 2 pennies.

The ternary operator looks attractive and can reduce the amount of code that you write. I know this but I still don't use it. I think PHP is an awesome language and a major contributing factor to its awesomeness is its simplicity. It's a relatively easy language to learn and I think that the wide spread use of the ternary operator would only increase the barrier to entry [not a good thing!]

Also, I find it interesting that the ternary operator is hardly ever referenced in the comments and code examples at PHP.net. Indeed chapter 16 "Control Structures" of the manual hardly mentions it at all.

Ternary operator code example

In case you've no idea what this post is about.

Before: no ternary operator, easy to understand

if ($treat == 'cream') {
    $cat = 'Happy!';
} else {
    $cat = 'Not so happy.';
}

After: ternary operator in use, less code but not so easy to understand

$cat = ($treat == 'cream') ? 'Happy!' : 'Not so happy.';

Tagged with: code, php, programming


1 Response to “Ternary Operator in PHP”

  1. Michael wrote,

    Personally I use the ternary operator spaced out over several lines. This is very readable and much quicker to see at a glance what is happening than by following the ins and outs of an if…else… block.

    Using your example:

    @$cat =
        $treat == 'cream'
        ? 'Happy!'
        : 'Not so happy.';@
    

    (If the formatting does not show I indent the ternary operator under the assignment.)

Add Your Comment

Use the form below to add your comment. Markdown syntax is available. Note, comments are moderated by me for spam filtering. Alternatively, feel free to contact me privately.