0
0
PHPprogramming~15 mins

Null coalescing operator in PHP - Deep Dive

Choose your learning style9 modes available
Overview - Null coalescing operator
What is it?
The null coalescing operator in PHP is a simple way to check if a value exists and is not null. It helps you pick the first value that is set and not null from a list of options. This operator is written as ?? and is often used to provide default values when something might be missing. It makes your code shorter and easier to read.
Why it matters
Without the null coalescing operator, you would need longer code to check if a variable exists and is not null before using it. This can make your code messy and harder to maintain. The operator solves this by giving a clean, quick way to handle missing or null values, which is very common when working with user input, databases, or APIs. It helps prevent errors and keeps programs running smoothly.
Where it fits
Before learning the null coalescing operator, you should understand basic PHP variables, the concept of null, and simple conditional statements like if-else. After this, you can learn about more advanced error handling, the ternary operator, and PHP 7+ features that improve code clarity and safety.
Mental Model
Core Idea
The null coalescing operator returns the first value that exists and is not null from a list of options.
Think of it like...
It's like choosing the first available seat in a row: you check each seat in order and sit in the first one that isn't empty.
Value1 ?? Value2 ?? Value3
  │        │        │
  ├─ if set and not null ──> return Value1
  ├─ else check next ──> Value2
  ├─ else check next ──> Value3
  └─ if none set, returns null
Build-Up - 7 Steps
1
FoundationUnderstanding null and isset
🤔
Concept: Learn what null means and how to check if a variable exists using isset.
In PHP, null means a variable has no value. The isset() function checks if a variable exists and is not null. Example: $var = null; var_dump(isset($var)); // false $var2 = 5; var_dump(isset($var2)); // true
Result
isset returns false for null variables and true for variables with any value.
Knowing how to check if a variable exists and is not null is the foundation for using the null coalescing operator.
2
FoundationUsing if-else to handle null values
🤔
Concept: Learn how to use if-else statements to provide default values when variables are null or missing.
Before the null coalescing operator, you might write: if (isset($name)) { $userName = $name; } else { $userName = 'Guest'; } echo $userName;
Result
If $name is set, it prints its value; otherwise, it prints 'Guest'.
This shows the common pattern of checking for a value and providing a fallback, which the null coalescing operator simplifies.
3
IntermediateIntroducing the null coalescing operator
🤔Before reading on: do you think the null coalescing operator can replace both isset and if-else checks? Commit to your answer.
Concept: The null coalescing operator ?? returns the first operand if it exists and is not null; otherwise, it returns the second operand.
Instead of if-else, you can write: $userName = $name ?? 'Guest'; echo $userName; This means: use $name if set and not null; otherwise, use 'Guest'.
Result
The output is the value of $name if it exists; otherwise, 'Guest'.
Understanding that ?? combines existence and null checks into one concise operator improves code readability and reduces errors.
4
IntermediateChaining multiple null coalescing operators
🤔Before reading on: do you think you can chain more than two values with ?? to find the first non-null? Commit to your answer.
Concept: You can chain ?? operators to check multiple variables in order and pick the first one that is set and not null.
$value = $a ?? $b ?? $c ?? 'default'; // This picks the first variable that exists and is not null, or 'default' if none do.
Result
The variable $value holds the first non-null value among $a, $b, $c, or 'default'.
Chaining ?? operators allows elegant fallback chains without nested if-else statements.
5
IntermediateDifference between ?? and ternary operator
🤔Before reading on: does ?? check for null only, or also for false and empty values? Commit to your answer.
Concept: The null coalescing operator only checks if a value is set and not null, unlike the ternary operator which can check any condition.
Example: $val = false; $result1 = $val ?? 'default'; // false because $val is set and not null $result2 = $val ? $val : 'default'; // 'default' because false is treated as falsey So ?? is about null, not false or empty.
Result
$result1 is false; $result2 is 'default'.
Knowing this difference prevents bugs when you want to treat false or empty strings differently from null.
6
AdvancedUsing ?? with array keys and undefined variables
🤔Before reading on: do you think ?? can safely check array keys that might not exist without errors? Commit to your answer.
Concept: The null coalescing operator can check if an array key exists without causing warnings, unlike direct access.
$arr = ['name' => 'Alice']; echo $arr['name'] ?? 'Unknown'; // prints 'Alice' echo $arr['age'] ?? 'Unknown'; // prints 'Unknown' without error Direct access $arr['age'] would cause a warning if key missing.
Result
Using ?? avoids warnings and provides safe defaults for missing array keys.
This makes ?? very useful for working with arrays and user input where keys may be missing.
7
ExpertNull coalescing operator internals and short-circuiting
🤔Before reading on: does the right side of ?? always evaluate, or only if the left side is null? Commit to your answer.
Concept: The right side of ?? is only evaluated if the left side is not set or is null, enabling efficient short-circuit evaluation.
Example: function getDefault() { echo 'Default called'; return 'default'; } $value = $var ?? getDefault(); If $var is set and not null, getDefault() is never called. This behavior saves resources and avoids side effects.
Result
The function getDefault() runs only if $var is null or not set.
Understanding short-circuiting helps write efficient code and avoid unintended function calls.
Under the Hood
At runtime, PHP evaluates the left operand of the ?? operator first. If it exists and is not null, PHP returns it immediately without evaluating the right operand. If the left operand is missing or null, PHP evaluates and returns the right operand. This short-circuit behavior prevents unnecessary computation and avoids warnings from undefined variables or array keys.
Why designed this way?
The operator was introduced in PHP 7 to simplify common patterns of checking for variable existence and null values, which previously required verbose code with isset() and ternary operators. The design balances readability, performance, and backward compatibility, avoiding errors from undefined variables while keeping code concise.
┌─────────────┐      ┌───────────────┐
│ Left operand│─────▶│ Is set & not  │
│   (value)   │      │    null?      │
└─────────────┘      └──────┬────────┘
                              │Yes
                              ▼
                      ┌─────────────┐
                      │ Return left │
                      │   operand   │
                      └─────────────┘
                              │No
                              ▼
                      ┌─────────────┐
                      │ Evaluate &  │
                      │ return right│
                      │  operand    │
                      └─────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does ?? treat false or empty string as null? Commit to yes or no.
Common Belief:Some think ?? treats false, 0, or empty string as null and skips them.
Tap to reveal reality
Reality:The operator only treats null or unset variables as missing; false, 0, and empty strings are valid values and returned as is.
Why it matters:Misunderstanding this can cause bugs where valid falsey values are ignored unintentionally.
Quick: Can ?? cause warnings if used on undefined variables? Commit to yes or no.
Common Belief:Some believe using ?? on undefined variables causes warnings like direct access.
Tap to reveal reality
Reality:Using ?? on undefined variables does NOT cause warnings; it safely checks existence.
Why it matters:This safety is a key advantage of ??, and not knowing it leads to unnecessarily complex code.
Quick: Does chaining ?? operators evaluate all operands? Commit to yes or no.
Common Belief:Some think all operands in a chain of ?? are always evaluated.
Tap to reveal reality
Reality:Only operands up to the first non-null value are evaluated; the rest are skipped.
Why it matters:Knowing this prevents performance issues and unexpected side effects from evaluating unnecessary expressions.
Quick: Is ?? the same as the ternary operator ?: ? Commit to yes or no.
Common Belief:Some assume ?? and ?: behave the same way.
Tap to reveal reality
Reality:They differ: ?: checks truthiness, while ?? checks only for null or unset.
Why it matters:Confusing them can cause logic errors, especially when false or empty values are involved.
Expert Zone
1
The null coalescing operator does not trigger __get() magic methods on objects when checking properties, unlike isset(), which can affect lazy loading patterns.
2
When used with expressions that have side effects, only the necessary expressions are evaluated due to short-circuiting, which can be leveraged for performance optimization.
3
In PHP 7.4+, the null coalescing assignment operator (??=) extends ?? by assigning the right operand to the left variable if it is null or unset, enabling concise initialization.
When NOT to use
Avoid using ?? when you need to check for false, empty strings, or zero values because ?? treats them as valid and returns them. Instead, use the ternary operator or explicit checks. Also, for complex conditions or when side effects matter, prefer clearer if-else statements.
Production Patterns
In real-world PHP applications, ?? is widely used for handling user input, configuration arrays, and optional parameters. It is common to see chained ?? operators to provide multiple fallback values. The null coalescing assignment operator ??= is used to initialize variables only if they are not already set, reducing boilerplate code.
Connections
Ternary operator
Related operator with different condition checks
Understanding the difference between ?? and ?: helps write precise conditional logic, especially when dealing with falsey values.
Optional chaining (?.) in programming
Builds-on similar safety checks for null or undefined values
Knowing ?? complements optional chaining, as both help safely access values that might be missing or null, improving code robustness.
Decision making in everyday life
Same pattern of choosing the first available option
Recognizing this pattern in daily choices, like picking the first open store, helps internalize how ?? selects the first valid value.
Common Pitfalls
#1Assuming ?? treats false or empty string as null and skips them.
Wrong approach:$value = $var ?? 'default'; // $var is false, expecting 'default' but gets false
Correct approach:$value = isset($var) && $var !== null ? $var : 'default'; // explicitly check for null
Root cause:Misunderstanding that ?? only checks for null or unset, not false or empty values.
#2Using ?? on variables with side effects expecting all expressions to run.
Wrong approach:$value = expensiveFunction() ?? anotherFunction(); // expects both functions to run
Correct approach:$value = expensiveFunction() ?: anotherFunction(); // or control evaluation explicitly
Root cause:Not realizing ?? short-circuits and only evaluates the right side if left is null or unset.
#3Using ?? when you want to check for false or empty values as well.
Wrong approach:$value = $var ?? 'default'; // $var is 0, but you want 'default'
Correct approach:$value = $var ? $var : 'default'; // use ternary for truthy check
Root cause:Confusing null coalescing with truthiness checks.
Key Takeaways
The null coalescing operator ?? returns the first operand that exists and is not null, simplifying common checks.
It safely handles undefined variables and array keys without warnings, making code cleaner and more robust.
Unlike the ternary operator, ?? only checks for null or unset, not false or empty values, which is an important distinction.
Chaining ?? operators allows elegant fallback sequences, and its short-circuiting behavior improves performance.
Understanding when and how to use ?? prevents common bugs and leads to clearer, more maintainable PHP code.