New Shorthand Form of the Ternary Operator in PHP 5.3
24 Apr 2010Hi 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:
[sourcecode language="php"]
// Instead of this
echo ($article->getAuthor())?$article->getAuthor():"Anonymous";
// We have a much shorter form
echo ($article->getAuthor())?:"Anonymous";
[/sourcecode]