The Null Operators: ?? and ?->
Pageturn's search page reads ?page=2 from the address bar, but on the first visit there is no page at all. Elsewhere, an order may or may not have a customer record attached. PHP code spends a lot of time asking "is this missing?", and two short operators answer that neatly.
The rule
??supplies a fallback for missing;?->stops safely at null.
The null coalescing operator ?? returns its left side if it exists and is not null, otherwise its right side:
<?php
$page = $_GET["page"] ?? 1; // 1 when page is absent
$subtitle = $book["subtitle"] ?? ""; // "" when there is no subtitleCrucially, ?? does not warn about a missing key or variable: it checks the left side like isset(), then picks. That makes it the standard way to read optional input.
It checks only for null or missing. A value of 0, "" or false is kept:
$discount = 0;
echo $discount ?? 10; // 0: zero is a real value
echo $discount ?: 10; // 10: ?: falls back on anything falsyThe assignment form ??= sets a variable only if it is currently null or missing: $name ??= "Guest";.
The nullsafe operator ?-> (PHP 8.0) is for objects, a topic beyond this course. You read an object's property or call its method with ->, as in $order->customer. If $order is null, reading a property gives a warning and calling a method is a fatal error. With ?->, the whole chain stops and gives null instead:
$email = $order?->customer?->email; // null if order or customer is nullCombine the two for a display value: $order?->customer?->email ?? "no email".
The shortcut
Ask "could this be missing, and what should I use then?"
- Missing array key or variable →
$x ?? fallback. - A step in an object chain might be null →
?->on that step. - A real
0or""must count as missing →?:, not??.
The risk
$_GET["page"]does not exist on the first visit. Reading it directly gives a warning and null.
Drills
Answer fast — trust the rule.
With $discount = 0;, what is $discount ?? 10?
What does $_GET["sort"] ?? "title" do when sort is not in the URL?
If $order is null, what is $order?->customer?->email?
Which line sets $name to "Guest" only if it is null or unset?
A form field may arrive as an empty string, which should count as missing. Which operator gives a fallback for it?
Remember
??supplies a fallback for missing;?->stops safely at null.- Shortcut: ask "could this be missing, and what then?"
- Trap:
??keeps0,""andfalse; use?:when those should count as missing.
