When to Use PHP’s Ternary (?:) vs. Null Coalescing (??) Operators

This guide explains the differences between PHP’s ternary (?:) and null‑coalescing (??) operators, showing how each handles truthy values, nulls, and undefined variables with practical code examples and common pitfalls.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
When to Use PHP’s Ternary (?:) vs. Null Coalescing (??) Operators

Introduction

In PHP, the ternary operator ( ?:) and the null‑coalescing operator ( ??) are often used interchangeably, but they serve distinct purposes. This article explores their behavior, demonstrates usage with examples, and highlights typical traps developers encounter.

PHP Ternary Operator (?:)

The ternary operator provides a concise way to write an if‑else statement.

// Traditional if‑else
if ($payload['name']) {
    $displayName = $payload['name'];
} else {
    $displayName = 'Guest';
}

Using the ternary operator:

$displayName = $payload['name'] ? $payload['name'] : 'Guest';

Further shortened with the Elvis form:

$displayName = $payload['name'] ?: 'Guest';

When the array key is missing, the expression throws an Undefined array key error because the variable is accessed before the check.

ErrorException: Undefined array key "name"

The ternary operator evaluates the truthiness of the left‑hand value; if it is falsy (e.g., '', null, 0, false), the right‑hand value is returned.

PHP Null‑Coalescing Operator (??)

The null‑coalescing operator works similarly but safely handles undefined variables without raising an error.

$displayName = $payload['name'] ?? 'Guest';

This is equivalent to:

$displayName = isset($payload['name']) ? $payload['name'] : 'Guest';

If the name key is absent, ?? returns the right‑hand value without throwing an exception.

$payload = [];
$displayName = $payload['name'] ?? 'Guest'; // returns 'Guest'

The key distinction is that ?? only checks for null or undefined values, whereas ?: checks the broader concept of truthiness.

Common Pitfalls with Null‑Coalescing

A frequent mistake is using ?? to mask typographical errors in array keys, which silently falls back to the default value.

$payload = ['first_name' => 'Ash'];
$firstName = $payload['frist_name'] ?? 'Guest'; // returns 'Guest' silently

Switching to the ternary operator reveals the mistake because accessing an undefined key triggers an error:

$firstName = $payload['frist_name'] ?: 'Guest';
// ErrorException: Undefined array key "first_name"

Which Operator Should You Use?

Both operators have valid use cases:

Use ?: when the variable is guaranteed to exist and you need to evaluate its truthiness.

Use ?? when you want to handle missing or null values gracefully without errors.

Choosing the right operator depends on the specific data handling requirements of your codebase.

Conclusion

This article compared PHP’s ternary ( ?:) and null‑coalescing ( ??) operators, illustrating how they differ in truthiness checking versus existence checking, and providing guidance on when to prefer each.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Code examplesternary operatorcommon pitfallsnull coalescing
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.