Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 147 ยท Operators

Null Coalescing, Ternary and Nullsafe Operators

Learn PHP's conditional operators - the ternary ?:, the short ternary, null coalescing ?? and ??=, and the nullsafe ?-> operator, plus the precedence traps to avoid.

A lot of everyday code boils down to "use this value, or else that one". Show the visitor's name, or "Guest" if there isn't one. Use the page number from the URL, or page 1. Read the city from the user's address, unless there's no address. You could write an if statement every time, but PHP has a small family of operators that say the same thing in a single expression.

This lesson covers all of them: the ternary operator ? :, its short form ?:, the null coalescing operator ?? and its assignment form ??=, and the nullsafe operator ?-> added in PHP 8.0. You'll also learn exactly which values each one treats as "missing", because that's where the real differences (and most bugs) are. The Booleans and null lesson gave a preview of ??; here you get the full picture.

The ternary operator

The ternary operator takes three operands, which is where its name comes from:

PHP
$result = condition ? valueIfTrue : valueIfFalse;

PHP evaluates the condition first. If it's truthy, the whole expression becomes the second operand; otherwise it becomes the third. Only one of the two branches is evaluated, so a function call in the branch that isn't chosen never runs.

PHP Choosing a value with the ternary operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice the parentheses around the ternary in the second and third echo lines. The concatenation operator . binds more tightly than ?, so without them PHP would glue the strings together first and use the whole string as the condition. When a ternary sits inside a bigger expression, wrap it in parentheses.

The ternary is an expression, which means it produces a value you can assign, return, pass to a function or echo. An if statement can't do that. On the other hand, a ternary is the wrong tool when the branches do things (save a file, send an email) instead of producing a value. Use if, elseif and else for actions and keep ternaries for picking values.

Nested ternaries need parentheses

Older PHP let you chain ternaries without parentheses, but it grouped them from the left, which is the opposite of nearly every other language, and the results surprised everyone. Since PHP 8.0, an unparenthesized nested ternary is a compile error, so the whole script refuses to run. This example fails on purpose:

PHP An unparenthesized nested ternary (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The error message tells you exactly how to fix it: add parentheses to say which grouping you mean. The readable choice is to nest in the "else" branch:

PHP
$grade = $score >= 90 ? 'A' : ($score >= 70 ? 'B' : 'C');

Even with parentheses, two levels is about the limit before a reader has to stop and decode it. For a grade table, a match expression is clearer: match (true) { $score >= 90 => 'A', $score >= 70 => 'B', default => 'C' }.

The short ternary ?:

If the value you test is also the value you want when it's truthy, you can leave out the middle operand:

PHP
$display = $nickname ?: 'Anonymous';
// same as: $display = $nickname ? $nickname : 'Anonymous';

This short ternary, sometimes called the "Elvis operator" (tilt your head to see the hair), returns the left operand if it's truthy and the right operand otherwise. The left side is evaluated only once, which matters if it's a function call.

The catch is the word truthy. Every falsy value counts as "missing": null, false, 0, 0.0, '', '0' and the empty array. Sometimes that's exactly what you want, such as replacing an empty form field with a default. Sometimes it's a bug: a quantity of 0 or a string '0' is real data, and ?: throws it away.

The null coalescing operator ??

The null coalescing operator ?? (PHP 7.0) returns its left operand if that operand exists and is not null, and the right operand otherwise:

PHP
$page = $_GET['page'] ?? 1;

Two things make ?? special:

  1. Only null counts as missing. 0, '', false and '0' are all kept.
  2. It doesn't warn about things that don't exist. An undefined variable, a missing array key or a missing property on the left side quietly falls through to the default. That's the same check isset() makes, so $a ?? $b is shorthand for isset($a) ? $a : $b, except the left side is evaluated only once.

The next example compares ?? and ?: on the same data. Run it and look at the warnings: the short ternary complains about the missing key, the null coalescing operator doesn't.

PHP Null coalescing versus the short ternary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The volume of 0 survives ?? but is replaced by ?:. The empty theme behaves the same way. For the missing lang key both operators give en, but the short ternary also prints Warning: Undefined array key "lang", because it really does read the key.

Tip: Reach for ?? when you're asking "was this value provided?", which is most of the time with request data, configuration arrays and optional fields. Use ?: only when an empty value should be replaced too, and you're sure the left side exists.

Chaining and nesting

?? groups from the right, so you can chain it to try several sources in order. The first one that exists and isn't null wins:

PHP Falling back through several sources

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The nested lookups show another strength: if any level of the path is missing, ?? falls back without a single warning. Writing the same thing with isset() and if would take several lines.

The precedence trap

?? has a very low precedence: lower than arithmetic, concatenation and comparisons. So PHP reads everything to its right as one operand:

PHP Why ?? usually needs parentheses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Without parentheses, the existing value 4 is returned unchanged, and the + 1 only applies to the default. The rule of thumb is simple: whenever ?? is part of a larger expression, put parentheses around it.

The null coalescing assignment ??=

PHP 7.4 added ??=, which assigns a value only if the variable (or array element or property) is undefined or null:

PHP
$options['timeout'] ??= 30;
// same as: $options['timeout'] = $options['timeout'] ?? 30;

It's perfect for filling in defaults without overwriting what the caller already set, and for building up arrays of groups:

PHP Filling defaults with ??=

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In the grouping loop, $groups[$letter] ??= [] creates an empty list the first time a letter appears and leaves it alone afterwards. (PHP would actually create the array for you on $groups[$letter][] = ..., but the explicit line makes the intent obvious and is handy when the default is something other than an empty array.) Loops like this one are covered in foreach Loops.

The nullsafe operator ?->

Objects are covered from Object-Oriented Programming in PHP onward, but one operator belongs here. When you call a method or read a property with -> and the left side is null, PHP stops with an error:

TEXT
Fatal error: Uncaught Error: Call to a member function getAddress() on null

The nullsafe operator ?-> (PHP 8.0) checks first. If the left side is null, the whole chain stops and evaluates to null. Otherwise it behaves exactly like ->. It's ideal for optional relationships, such as a customer who may not have an address yet:

PHP Optional chains with the nullsafe operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The two small classes use constructor property promotion, which you'll meet properly in Constructors and Destructors. The important line is the one inside the loop. Customer 1 has a full chain. Customer 2 exists but has no address, so getAddress() returns null and ?->city stops there. Customer 3 doesn't exist at all, so the chain stops at the very first ?->. Each time, ?? 'unknown' turns the final null into a friendly default.

Short-circuiting

When ?-> meets null, PHP skips the rest of the chain, including method arguments. Nothing to the right is evaluated:

PHP The rest of the chain is skipped

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

With a real logger, buildMessage() runs and its result is logged. With null, PHP never calls buildMessage() at all and the result is simply NULL.

What ?-> does not do

The nullsafe operator is narrower than it looks:

  • It only guards against null. If the left side is some other non-object, such as false or an integer, you still get an error or warning. If a property doesn't exist on a real object, you still get Warning: Undefined property. Add ?? default at the end when you want silence and a fallback.
  • It's read-only. You can't assign through it: $customer?->address = $a; is a compile error ("Can't use nullsafe operator in write context"), because PHP would have nowhere to write when the chain is null.
  • It isn't a reason to return null everywhere. A long chain of ?-> often means the code doesn't know whether data exists. When a value is required, an exception (see Exceptions) gives a much clearer failure than a silent null.

Choosing the right operator

You want Use Treats as missing
Pick one of two values by a condition $c ? $a : $b (any condition)
Replace any empty or falsy value $a ?: $b null, false, 0, '', '0', [] (warns if undefined)
A default when a value isn't set $a ?? $b undefined or null only, no warnings
Set a default in place $a ??= $b undefined or null only
Call a method or read a property on something that may be null $obj?->method() null only

All of these return values, so they combine well: $user?->profile?->nickname ?: 'Anonymous' reads the nickname safely and replaces an empty one too. Keep each line simple enough to read at a glance, and switch to if or match when it isn't.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does echo $qty ?? 10; print when $qty = 0;?

    ?? only falls back when the left side is undefined or null. 0 is a real value, so it is printed.
  2. 2. Which line prints a warning when the array $a has no key "x"?

    The short ternary reads the key like a normal expression, so PHP warns about the undefined key. ??, ??= and isset() check for existence without warning.
  3. 3. With $stock = ['apples' => 2];, what does echo $stock['apples'] ?? 0 + 5; print?

    ?? has lower precedence than +, so this means $stock['apples'] ?? (0 + 5). The key exists, so 2 is printed. Write ($stock['apples'] ?? 0) + 5 to get 7.
  4. 4. What happens when PHP 8 runs a nested ternary without parentheses, such as $a ? 'x' : $b ? 'y' : 'z'?

    Since PHP 8.0, unparenthesized nested ternaries are a fatal compile error. Add parentheses to say which grouping you mean.
  5. 5. If $order is null, what does $order?->total(calculateTax()) do?

    When the nullsafe operator meets null it short-circuits the rest of the chain, including method arguments, and the whole expression is null.

Summary

  • The ternary cond ? a : b picks one of two values; only the chosen branch is evaluated. Wrap it in parentheses inside bigger expressions.
  • Nested ternaries must be parenthesized since PHP 8.0; for more than two levels, use match.
  • The short ternary a ?: b returns a if it's truthy, so it replaces 0, '', '0' and other falsy values, and it warns about undefined variables and keys.
  • Null coalescing a ?? b returns a unless it's undefined or null, never warns about missing variables, keys or properties, and chains from left to right through several fallbacks.
  • ?? has very low precedence: write ($a ?? 0) + 1, not $a ?? 0 + 1.
  • ??= (PHP 7.4) assigns a default only when the target is undefined or null.
  • The nullsafe operator ?-> (PHP 8.0) stops a chain at the first null and skips everything to its right; it can't be used for assignment and only guards against null.

Next: Bitwise, String, Array and Pipe Operators