Null Coalescing, Ternary and Elvis

6.Null Coalescing, Ternary and Elvis

M

In this chapter

We'll learn the operators that choose between values: ?? and ??= for missing values, the ternary operator ? : for choosing one of two values, and the short ?: (the "Elvis" operator) — plus why ?: turned a 0% discount into 10%, and why nested ternaries need brackets.

13–15 min

The Problem in Real Life

The booking form now has three optional fields: a discount code, a note, and the number of people. Mia fills in defaults with a short operator she found online: $discountPercent = $input ?: 10; — "use the input, or 10 if there isn't one".

Olivia tests it with a staff code that gives exactly 0% — no discount, just a tag. The booking shows a 10% discount. Then Mia tries a test page without any discount field at all, and the log fills with Undefined variable warnings again.

"Two different questions," says Marcus. "Is it missing? and Is it empty? PHP has a different operator for each. You picked the one that thinks zero is empty."

M

0 was a real answer. Why did PHP replace it with 10?

Mia

Missing vs. Empty vs. Zero

Optional fields

Discount, note and number of people may each be missing — and each needs a sensible default.

Zero treated as nothing

?: replaces 0, "" and "0" — even when they're real answers.

Choosing one of two

"Member price or normal price" shouldn't need a five-line if.

Null Coalescing, Ternary and Elvis

Operators that choose a value: this chapter's operators all pick one of two values, but they ask different questions. Getting the question right is the whole skill:

  • ??: "is the left side missing or null? Then use the right side."
  • ??=: "if this variable is missing or null, set it."
  • The ternary, ? : "is this condition true? Then this value, otherwise that one."
  • The short ternary, ?: (Elvis): "is the left side truthy? Then use it, otherwise the right side."

The null coalescing operator, ??: you met it in Act 03. $a ?? $b gives $a if it exists and isn't null, otherwise $b — and it never warns about a missing variable. It only cares about "missing or null": 0, "" and false are real values, so they're kept. You can chain it: $fromForm ?? $fromProfile ?? "guest" takes the first one that's set. This is the right operator for optional input.

?? keeps real values and chains
<?php
$discountPercent = 0;
var_dump($discountPercent ?? 10); // int(0): 0 is a real value
var_dump($missing ?? 10); // int(10): no warning
$nameFromForm = null;
$nameFromProfile = "Zoë";
echo $nameFromForm ?? $nameFromProfile ?? "guest", "\n"; // Zoë

The null coalescing assignment, ??=: $note ??= "No note"; sets $note only if it's missing or null; if it already has a value, nothing changes. It's the compound-assignment version of ?? (chapter 1), and perfect for filling in defaults at the top of a file or function.

??= sets a default only when needed
<?php
$note = null;
$note ??= "No note";
var_dump($note); // string(7) "No note"
$note ??= "Something else";
var_dump($note); // still "No note": it already had a value

The ternary operator, ? : condition ? valueIfTrue : valueIfFalse picks one of two values. $isMember ? 2000 : 2500 gives 2000 for members and 2500 for everyone else. It's called ternary because it has three parts. Use it for short choices between two values; when the choice involves several statements, use if (Act 06). Don't put a ternary inside another without brackets: $a ? 1 : $b ? 2 : 3 is a fatal error in PHP 8, because it's too easy to misread. Add brackets to show which choice is inside which — or, better, use match (Act 06).

The ternary operator
<?php
$isMember = true;
$pricePence = $isMember ? 2000 : 2500;
echo $pricePence, "\n"; // 2000
$hour = 15;
// echo $hour < 12 ? "morning" : $hour < 17 ? "afternoon" : "evening";
// Fatal error: Unparenthesized `a ? b : c ? d : e` is not supported
echo $hour < 12 ? "morning" : ($hour < 17 ? "afternoon" : "evening"); // afternoon

The short ternary, ?: — called Elvis: leave out the middle part, and you get $a ?: $b: "$a if it's truthy, otherwise $b". (It's nicknamed the Elvis operator because ?: looks like a face with Elvis's hairstyle.) Truthy means "converts to true" (Act 04, chapter 7) — so 0, 0.0, "", "0", null and [] are all replaced. That's Mia's bug: the 0% discount is falsy, so ?: swapped it for 10. And unlike ??, Elvis does warn when the left side is a missing variable. Use ?: only when every falsy value really means "use the default" — for example, an empty name should become "guest".

Mia's bug: Elvis replaces 0
<?php
$discountPercent = 0; // a real 0% staff code
var_dump($discountPercent ?: 10); // int(10) — wrong
var_dump($discountPercent ?? 10); // int(0) — right
$name = "";
echo $name ?: "guest", "\n"; // guest: here, empty really means "use the default"

Which one to use: the table below compares them on the values that matter. The quick rule: for missing input, use ??; for a two-way choice, use ? :; when empty really means default, use ?:; and when in doubt, ??.

Table — ?? vs. ?: on the values that matter
$value is$value ?? 10$value ?: 10
(never set)10 (no warning)10, with a warning
null1010
0010
"" (empty text)""10
"0""0"10
falsefalse10
151515

Key Takeaway

$a ?? $b replaces only missing or null values, without warnings; ??= assigns a default only when needed. cond ? x : y chooses between two values — nested ternaries need brackets. $a ?: $b (Elvis) replaces every falsy value, including 0 and "", and warns on missing variables. For optional input, use ??.

Why This Matters

Optional values are everywhere in BookBay's forms, links and settings. Choosing ?? for "missing" and ?: only for "empty means default" is the difference between respecting a customer's real 0 and quietly overriding it.

The ternary keeps small choices on one readable line — and knowing its nesting rule saves Mia from the fatal error PHP 8 added exactly because nested ternaries were misread so often.

Mia replaces every ?: on optional input with ??, and the 0% staff code works. Now the double-booking line is fixed, the end times are right, and the defaults behave — but she still doesn't really know why && beats ||, or why -2 ** 2 was -4. "There's one table that answers all of that," says Marcus. That's the next chapter.