Skip to main content

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:

Prompt
Write a PHP script that sets a variable $age to 20, then uses the ternary operator to check if $age is 18 or more and assigns "old enough" or "not old enough" to a variable $vote, then prints $vote.
Output: PHP script

Ternary operator without variable

A variable isn't required. The ternary can go straight inside echo, which prints whichever value is chosen:

Prompt
Write a PHP script that sets a variable $age to 20, then uses the ternary operator directly inside an echo statement to output "old enough" if $age is 18 or more, or "not old enough" otherwise.
Output: PHP script

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":

Prompt
Write a PHP script that uses the null coalescing operator to check if a variable $color is set. If $color is set, echo its value. If not, echo "red". Do not define $color beforehand.
Output: PHP script

Null coalescing with defined variable

Now $color has been given a value, so that value is what you get, and the fallback is ignored:

Prompt
Write a PHP script that sets a variable $color to "blue", then uses the null coalescing operator to echo $color or "red" as a fallback.
Output: PHP script