How to do the shorthand conditional ternary in PHP

Engineering

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.

<?php

$a = false;
$b = 'b';

if ($a) {
  echo $a;
} else {
  echo $b;
}

That was the long hand way to do an if condition, which can ofcourse be shortened to a standard ternary condition as follows.

<?php

$a = false;
$b = 'b';

echo $a ? $a : $b;

And finally, this can be further compacted down using the shorthand conditional ternary operator.

<?php

$a = false;
$b = 'b';

echo $a ?: $b;

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.

<span>Hello there, <?php echo $fullName ?: 'Guest' ?></span>