Short Hand If
A simple if...else can be squeezed onto a single line, which keeps your code short. This form is called the ternary operator, a name that comes from its three parts: a condition, a value for when it is true, and a value for when it is false.
Ternary operator
Rather than spelling out a full if...else, this line picks one of two strings for $vote depending on $age:
Output: PHP script
<?php
$age = 20;
$vote = ($age >= 18) ? "old enough" : "not old enough";
echo $vote;
?>
Ternary operator without variable
A variable isn't required. The ternary can go straight inside echo, which prints whichever value is chosen:
Output: PHP script
<?php
$age = 20;
echo ($age >= 18) ? "old enough" : "not old enough";
?>
Null Coalescing Operator
The null coalescing operator (??) looks at the value on its left. If that value exists and isn't null, you get it back; if not, you get the value on its right. This makes it a handy, shorter replacement for a ternary when all you want to know is whether a variable is set.
Null coalescing with undefined variable
$color has not been defined in this script, so ?? falls back to "red":
Output: PHP script
<?php
echo $color ?? "red";
?>
Null coalescing with defined variable
Now $color has been given a value, so that value is what you get, and the fallback is ignored:
Output: PHP script
<?php
$color = "blue";
echo $color ?? "red";
?>