CodeBlanks Logo Icon CodeBlanks

The ternary operator

PHP course · Beginner · Lesson 39/116

Learn to write a conditional expression in one line with ? :.

The ternary operator

To write a condition in one line, use the ternary operator ? :. The structure is condition ? true_value : false_value. When the condition is true the part after the question mark is returned; when false the part after the colon.

For example, $label = $age >= 18 ? 'adult' : 'minor';. This replaces a short if/else but should be used for simple assignments to keep code readable.

The Elvis operator ?:

PHP's short ternary is the Elvis operator written ?:. $a ?: $b returns $a when it is truthy, otherwise $b. It is short for $a ? $a : $b.

For example, $name = $input ?: 'Guest';. When $input is empty or false, 'Guest' is used. It saves you from writing the value twice.

Exercise Write an age label

The $age variable is already declared. With the ternary operator, assign to $label: when $age >= 18 use 'adult', otherwise 'minor'. Then print with echo $label;. Do not use if/else.

Show example solution
'minor';
Example solution:
<?php
$age = 20;
// Age label
$label = $age >= 18 ? 'adult' : 'minor';
echo $label;

Test yourself

  1. Write the ternary colon

    $label = $age >= 18 ? 'adult' ____ 'minor';
    echo $label;
    Show answer
    $label = $age >= 18 ? 'adult' : 'minor';
    echo $label;
  2. What is the output of $x = 5 > 3 ? 'yes' : 'no'; echo $x;?

    $x = 5 > 3 ? 'yes' : 'no';
    echo $x;
    • no
    • yes
    • true
    • 5
    Show answer

    yes — Correct. 5 > 3 is true, so 'yes' is returned and printed.

  3. Match the ternary parts

    ?
    True branch
    :
    False branch
    condition
    Boolean expression
    ?:
    Elvis operator

All lessons in Beginner