How to use the PHP Ternary Operator

In this tutorial I will show you how to use the PHP ternary operator. PHP Ternary operator logic is the process of using “(condition) ? (true return value) : (false return value)” statements to shorten your if/else structures. It is called the ternary operator because it takes three operands – a condition, a result for true, and a result for false.

Following example with if/else logic:

$a = 6;
$b = 10;
if ($a > $b) {
     echo "$a is greater then $b";
} else {
     echo "$b is greater then $a";

Ternary Operator

$a = 6;
$b = 10;
echo ($a > $b) ? "$a is greater then $b" : "$b is greater then $a";

Ternary operator makes coding simple if/else logic quicker, makes code shorter, you can do your if/else logic inline with output instead of breaking your output building for if/else statements.

Since PHP 5.3 it is possible to abbreviate ternary statements even more by excluding the middle expression. If the test expression evaluates true in a boolean context, its value is returned. Otherwise, the alternative is returned instead.

$title = $_GET["title"] ?: "Mr.";