We’ve already discussed the ternary operator in another article. However, we haven’t yet covered the null coalescing operator (??
). And, because they are somewhat similar (but not identical), we’ll compare and analyze them in this article.
Ternary Operator (?:
)
The ternary operator is a shorthand for if ... else
and is used when we want to choose between two values based on a condition.
Example:
- Checks if
$afis == 1
- If true → returns
$user_id
- If false → returns
NULL
Null Coalescing Operator (??
)
The null coalescing operator is a shorthand for the following structure:
Example:
- Checks if
$_SESSION['request']
exists and is not null - If true →
$data = $_SESSION['request']
- If false →
$data = []
Graphic Example

Representation of the two examples from the diagrams:
ChatGPT-Style Summary
Using ChatGPT for a quick synthesis, we can outline the differences as follows:
Characteristic | Ternary (?: ) |
Null Coalescing (?? ) |
---|---|---|
Purpose | Choose between two values based on a condition | Choose the first non-null/existing value |
Checks | Any logical condition (boolean expression) | Only if isset() and not null (!= null ) |
Example | $x > 5 ? 'big' : 'small'; |
$x ?? 'default'; |
Long equivalent | if (...) { ... } else { ... } |
if (isset(...)) { ... } else { ... } |
Number of values checked | Two (true/false) | Can be a chain ($a ?? $b ?? $c ) |
Possible outcomes | Two possible values | First non-null value in the chain |
Typical use case | Choose based on a condition | Provide a default if value is null |
In short:
- If we have a logical condition and two possible outcomes → use the ternary operator.
- If we want to check whether a variable exists and is not null, otherwise provide a default value → use
??
.
Mnemonic trick:
- Ternary = “T” from Test → tests a condition.
??
= “Two question marks” → asks if the variable exists and is not null.
Example for Differentiation
1 2 3 4 5 6 7 8 9 10 11 12 13 |
=== Ternary Operator === Case 1 (afis=1) → 123 Case 2 (afis=0) → NULL === Operator ?? === Case 1 (not set) → array ( ) Case 2 (set) → array ( 'id' => 45, ) Simple chain (null → default) → default Simple chain (set) → set |
So:
- The ternary operator decides based on a logical condition (true/false).
??
gives a default value if the first one does not exist or isnull
.- We can also use
??
in a string:$a ?? $b ?? $c
.