How to do the shorthand conditional ternary in PHP
PHP 5.3 added support for shorthand conditional ternary operators.
Most programmers are familiar with the ternary operators, and while most languages have their own way of performing shorthand conditional ternaries, however since PHP 5.3 supported was added to do this by leaving out the middle part of the condition.
Let’s take a quick look at all possible ways to do a condition in PHP, starting with the full traditional condition.
That was the long hand way to do an if condition, which can ofcourse be shortened to a standard ternary condition as follows.
And finally, this can be further compacted down using the shorthand conditional ternary operator.
If you are wondering where this might be useful, one of the most common use-cases is when presenting a default value in template/view files.
For example, the following code will print the users full name, otherwise Guest.
Damian Hodgkiss
Senior Staff Engineer at Sumo Group, leading development of AppSumo marketplace. Technical solopreneur with 25+ years of experience building SaaS products.