Skip to content

PHP Tutorial Operators

Null Coalescing Operator

Lesson 55 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

The null coalescing operator ?? gives you a default value when something is missing or null.

index.php
PHP
<?php
$username = null;

echo $username ?? "Guest";
Output
OUTPUT
Guest

It reads as: “use $username, but if it does not exist or is null, use Guest.”

No warning for missing keys

The big advantage is that ?? never complains about a missing variable or array key.

index.php
PHP
<?php
$user = ["name" => "Lina"];

echo $user["name"] ?? "Unknown";
echo "\n";
echo $user["email"] ?? "No email";
Output
OUTPUT
Lina
No email

Without ??, reading $user["email"] would raise a warning about an undefined key.

With form data

This is where ?? is used most. A form field may not be sent at all.

index.php
PHP
<?php
$page = $_GET["page"] ?? 1;
$search = $_POST["q"] ?? "";

Chaining

You can chain several ??. PHP uses the first value that exists and is not null.

index.php
PHP
<?php
$nickname = null;
$name = "Lina";

echo $nickname ?? $name ?? "Guest";
Output
OUTPUT
Lina

?? vs ?:

?? checks whether a value is missing or null. The short ternary ?: checks whether it is falsy (0, “”, “0”, false, empty array).

index.php
PHP
<?php
$count = 0;

echo ($count ?? 10) . "\n";   // 0, because 0 is not null
echo ($count ?: 10);          // 10, because 0 is falsy
Output
OUTPUT
0
10

Use ?? when 0 or an empty string are valid values.

??= assigns a default

index.php
PHP
<?php
$config = [];
$config["debug"] ??= false;

var_dump($config["debug"]);
Output
OUTPUT
bool(false)
lightbulb
Introduced in PHP 7
The ?? operator has existed since PHP 7.0, and ??= since PHP 7.4. Both are safe on any current version.