preload

Ternary Operators in PHP: Shorthand If Else Statements

If-Else statements are a vital part of programming, however sometimes all the code that goes into writing are not required, especially if only only simple condition is needed. This is what the ternary operator is used for.

The ternary operator is a shorthand if/else statement. It allows developers to form conditions quickly and in a very readable fashion.

Here is the ternary syntax


(condition) ? true-stuff-here : false-stuff-here;

Here is an example of the ternary operator


$age = 20;

$response = ($age > 29) ? 'He's in his thirties' : 'He's not';

echo $response; // He's not

I hope you can see the usefulness in the ability for the ternary operator to easily perform conditional comparisons. Please however, refrain from using ‘nested ternary comparisons’ as the are very difficult to so read. It is so frowned upon by web developers that I’m not even going to post an example.

Leave a Reply

* Required
** Your Email is never shared