Skip to the workspace
Pebellslearn by building
Conditionals  ›  Capstone Project

The Null Operators: ?? and ?->

Null Coalescing Operator 14 minThe null coalescing operator ?? gives a fallback when a value is missing or null without a warning, and the nullsafe operator ?-> stops an object chain and returns null at the first null.

php / The Null Operators: ?? and ?->

Explore each scene at your own pace.

01 · The rule

The rule

The Null Operators: ?? and ?->

The null coalescing operator ?? gives a fallback when a value is missing or null without a warning, and the nullsafe operator ?-> stops an object chain and returns null at the first null.

Distinguish a missing value from a falsy value and follow null-safe access.

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 subtitle

Crucially, ?? 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 falsy

The 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 null

Combine the two for a display value: $order?->customer?->email ?? "no email".

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.