New Shorthand Form of the Ternary Operator in PHP 5.3


Hi PHP folks

I found myself writing using the ternary operator usually and new syntax make it even shorter

The ternary operator lets your code use the value of one expression or another, based on whether a third expression is true or false:
> ( expression1 ) ? expression2 : expression3;

In PHP 5.3 you can now omit the second expression in the list:
> ( expression1 ) ?: expression3;

This code evaluates to the value of expression1 if expression1 is true; otherwise it evaluates to the value of expression3.

Here is one simple example:

// Instead of this
echo ($article->getAuthor())?$article->getAuthor():"Anonymous";
// We have a much shorter form
echo ($article->getAuthor())?:"Anonymous";
Advertisements

3 thoughts on “New Shorthand Form of the Ternary Operator in PHP 5.3

  1. I’m not quite clear on your example. Does $article->getAuthor() return true? If it does, then isn’t the echo just going to put out “true”?

    It would be great to use this with “isset”. For instance I would like to use:

    echo isset($array[‘foo’]) ?: “”;

    This would be of great use when output from partially filled arrays (some keys are missing and the loop should just skip over uninitialized items. The alternatives right now are to make sure the array is properly filled always, or add the @ sign before echo like so:

    echo @$array[‘foo’] ?: “”;

    This could stifle other errors though, so it’s not ideal.

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