Null coalescing at the end of array or object accessing syntax will work perfectly well without any notices, warnings or errors so long as you are (respectively) only trying to access keys or properties (no method calls).

Code: (Demo) (the same for both with isset())

var_export($array['does']['not']['exist'] ?? 'nope');
    
echo "\n---\n";

var_export($obj->does->not->exist ?? 'nope');

Output:

'nope'
---
'nope'

Not even mixed access (a path containing keys and properties to a value) are problematic (the behavior remains the same when using isset()). (Demo)

var_export($obj->does[123]->not->exist[678]['foo'] ?? 'nope');
// nope

From PHP8.2, for scenarios where you want to use array_key_exists() (aka key_exists()) or property_exists(), you can use null-safe arrows and a null coalescing operator. (Demo)

var_export(
    key_exists(
        'foo',
        $obj?->does[123]?->not?->exist[678] ?? []
    )
    ? 'yep'
    : 'nope'
);

And

var_export(
    property_exists(
        $obj?->does[123]?->not?->exist[678] ?? (object) [],
        'foo'
    )
    ? 'yep'
    : 'nope'
);

The null-safe operator is necessary before chaining a method if the leftside nullable object is guaranteed to exist.

See Is there a "nullsafe operator" in PHP?

If you have a basic class like this:

class Test
{
    public function doThing($v) {
        return $v;
    }
}

Then you run this code:

$object = null;
var_export($object->doThing('foo') ?? 'oops');

You will get:

Fatal error: Uncaught Error: Call to a member function doThing() on null

If you instead run this code:

$object = null;
var_export($object?->doThing('foo'));

You will see that the doThing() method will not be reached and null will be displayed.

Differently from $object being assigned a null value, if $object isn't defined at all, you get Warning: Undefined variable $object. Warning Demo Fixed Demo

var_export($object?->doThing('foo')); // Warning
var_export(($object ?? null)?->doThing('foo')); // Fixed

So ultimately, don't use the null-safe operator unless you have methods later in your chain.

Also do not confuse the "null-safe operator" as meaning "undeclared-or-null-safe operator. If you are going to chain using the nullsafe operator, you must ensure that the operator is attached to an object or a null value.


Now that we have pipe operators to chain functions to data in PHP8.5, it can be said that functions can be chained to arrays, but in this context there is no need to defend or short circuit when a null value is encountered. The chained function may have no problem consuming null values. Demo

$a = null;
$a |> var_export(...);
Answer from mickmackusa on Stack Overflow
Top answer
1 of 1
14

Null coalescing at the end of array or object accessing syntax will work perfectly well without any notices, warnings or errors so long as you are (respectively) only trying to access keys or properties (no method calls).

Code: (Demo) (the same for both with isset())

var_export($array['does']['not']['exist'] ?? 'nope');
    
echo "\n---\n";

var_export($obj->does->not->exist ?? 'nope');

Output:

'nope'
---
'nope'

Not even mixed access (a path containing keys and properties to a value) are problematic (the behavior remains the same when using isset()). (Demo)

var_export($obj->does[123]->not->exist[678]['foo'] ?? 'nope');
// nope

From PHP8.2, for scenarios where you want to use array_key_exists() (aka key_exists()) or property_exists(), you can use null-safe arrows and a null coalescing operator. (Demo)

var_export(
    key_exists(
        'foo',
        $obj?->does[123]?->not?->exist[678] ?? []
    )
    ? 'yep'
    : 'nope'
);

And

var_export(
    property_exists(
        $obj?->does[123]?->not?->exist[678] ?? (object) [],
        'foo'
    )
    ? 'yep'
    : 'nope'
);

The null-safe operator is necessary before chaining a method if the leftside nullable object is guaranteed to exist.

See Is there a "nullsafe operator" in PHP?

If you have a basic class like this:

class Test
{
    public function doThing($v) {
        return $v;
    }
}

Then you run this code:

$object = null;
var_export($object->doThing('foo') ?? 'oops');

You will get:

Fatal error: Uncaught Error: Call to a member function doThing() on null

If you instead run this code:

$object = null;
var_export($object?->doThing('foo'));

You will see that the doThing() method will not be reached and null will be displayed.

Differently from $object being assigned a null value, if $object isn't defined at all, you get Warning: Undefined variable $object. Warning Demo Fixed Demo

var_export($object?->doThing('foo')); // Warning
var_export(($object ?? null)?->doThing('foo')); // Fixed

So ultimately, don't use the null-safe operator unless you have methods later in your chain.

Also do not confuse the "null-safe operator" as meaning "undeclared-or-null-safe operator. If you are going to chain using the nullsafe operator, you must ensure that the operator is attached to an object or a null value.


Now that we have pipe operators to chain functions to data in PHP8.5, it can be said that functions can be chained to arrays, but in this context there is no need to defend or short circuit when a null value is encountered. The chained function may have no problem consuming null values. Demo

$a = null;
$a |> var_export(...);
🌐
PHP
wiki.php.net › rfc › nullsafe_operator
PHP: rfc:nullsafe_operator
Since with short circuiting the array access ['baz'] will be completely skipped no notice is emitted. Lets look the most popular high-level programming languages (according to the Stack Overflow 2020 survey) and our sister language Hack to see how the nullsafe operator is implemented.
🌐
PHP.Watch
php.watch › versions › 8.0 › null-safe-operator
Null-safe operator - PHP 8.0 • PHP.Watch
The null-safe operator allows reading the value of property and method return value chaining, where the null-safe operator short-circuits the retrieval if the value is null, without causing any errors.
🌐
Stitcher
stitcher.io › blog › php-8-nullsafe-operator
PHP 8: the null safe operator | Stitcher.io
While you could use both operators to achieve the same result in this example, they also have specific edge cases only one of them can handle. For example, you can use the null coalescing operator in combination with array keys, while the nullsafe operator can't handle them:
Top answer
1 of 4
83

From PHP 8, you are able to use the null safe operator which combined with the null coalescing operator allows you to write code like:

echo $data->getMyObject()?->getName() ?? '';

By using ?-> instead of -> the chain of operators is terminated and the result will be null.

The operators that "look inside an object" are considered part of the chain.

  • Array access ([])
  • Property access (->)
  • Nullsafe property access (?->)
  • Static property access (::)
  • Method call (->)
  • Nullsafe method call (?->)
  • Static method call (::)

e.g. for the code:

$string = $data?->getObject()->getName() . " after";

if $data is null, that code would be equivalent to:

$string = null . " after";

As the string concatenation operator is not part of the 'chain' and so isn't short-circuited.

2 of 4
14

Nullsafe operator allows you to chain the calls avoiding checking whether every part of chain is not null (methods or properties of null variables).

PHP 8.0

$city = $user?->getAddress()?->city

Before PHP 8.0

$city = null;
if($user !== null) {
    $address = $user->getAddress();
    if($address !== null) {
        $city = $address->city;
    }
}

With null coalescing operator (it doesn't work with methods):

$city = null;
if($user !== null) {
    $city = $user->getAddress()->city ?? null;
}

Nullsafe operator suppresses errors:

Warning: Attempt to read property "city" on null in Fatal error:

Uncaught Error: Call to a member function getAddress() on null

However it doesn't work with array keys:

$user['admin']?->getAddress()?->city //Warning: Trying to access array offset on value of type null

$user = [];
$user['admin']?->getAddress()?->city //Warning: Undefined array key "admin"
🌐
DEV Community
dev.to › frknasir › php-null-safe-and-null-coalescing-operators-jg2
PHP null-safe and null-coalescing operators - DEV Community
July 6, 2021 - The null-safe operator supports method while the null-coalescing operator doesn't. The null-coalescing operator supports array while the null-safe operator doesn't. // this works $array = []; var_dump($array['mukulli']->kofa ?? null); // this ...
🌐
Exakat
exakat.io › home › null safe operator in practice
Null safe operator in practice - Exakat
December 20, 2023 - It only works on null values: there is no differences when calling a method on an integer or an array: Fatal error. The first impact of this operator is to prevent a pesky stop in execution, just because an object is not available.
🌐
Medium
medium.com › @prevailexcellent › mastering-null-safety-in-php-8-a-comprehensive-guide-to-using-the-null-safe-operator-47835ba1140b
Mastering Null Safety in PHP 8: A Comprehensive Guide to Using the Null Safe Operator | by Chimeremze Prevail Ejimadu | Medium
June 14, 2023 - So, let’s dive in and unlock the secrets of null safety in PHP 8! In PHP, dealing with null values can be error-prone and cumbersome. Traditional null checks involving if statements or ternary operators are often necessary to avoid null pointer exceptions when accessing object properties or invoking methods.
🌐
PHP
php.net › manual › en › migration70.new-features.php
PHP: New features - Manual
<?php function arraysSum(array ... type declarations can be found in the return type declarations. reference. The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary ...
Find elsewhere
🌐
Phpinternals
phpinternals.news › 65
PHP Internals News podcast :: Null safe operator
So you could do something like null safe operator bar equals foo, effectively assigning the string foo something that might or might not be null. I only learnt this recently. You can also foreach over an array into the property of an object, which I've never seen before in my 20 odd years writing PHP...
🌐
Medium
frknasir.medium.com › php-null-safe-and-null-coalescing-operators-727eda4a2073
PHP null-safe and null-coalescing operators | by Faruk Nasir | Medium
April 23, 2021 - The null-safe operator supports method while the null-coalescing operator doesn’t. The null-coalescing operator supports array while the null-safe operator doesn’t. // this works $array = [];var_dump($array['mukulli']->kofa ?? null); // this throws a warning var_dump($array['mukulli']?->kofa);// Warning: Undefined array key "key" ... class Order { public function date(): ?Carbon { /* … */ } // … }$order = new Order();var_dump($order->date()?->format('Y-m-d'));// null
🌐
dailycomputerscience
dailycomputerscience.com › post › exploring-the-php-8-nullsafe-operator
Exploring the PHP 8 Nullsafe Operator
December 12, 2025 - In this case, if either $user or $user->address is null, the expression will safely return null without throwing an error. This makes the code more concise and readable. The nullsafe operator works similarly to the existing object operator (->), but with a built-in check for null. When PHP encounters the ?-> operator, it first checks if the object on the left-hand side is null.
🌐
Exakat
php-dictionary.readthedocs.io › en › latest › dictionary › object-nullsafe-operator.ini.html
Object Nullsafe Operator ?-> — PHP Dictionary 1.0.0 documentation
January 10, 2025 - Object Nullsafe Operator is directly related to the Object operator : the difference is that the former keeps on executing when the support object is null, while the second stops with a fatal error. <?php $array = ['a' => (new stdClass)->a = 1, ]; // displays 1 echo $array['a']?->a; // displays ...
🌐
DEV Community
dev.to › bawa_geek › what-is-null-safety-operator-in-php-8-and-why-is-it-next-big-thing-in-php-377b
What is Null Safety Operator in PHP 8 and why is it next big thing in PHP - DEV Community
December 14, 2023 - The null-safe operator solves this by short-circuiting the property/method access, and returning null immediately if the left side of the operator is null, without executing the rest of the expression. PHP 8 new Features.
🌐
codestudy
codestudy.net › blog › is-there-a-null-safe-operator-for-accessing-array-data
Is There a Null Safe Operator for Array Data Access in PHP? Alternative Methods Explained — codestudy.net
Whether you’re working with simple ... introduced the null safe operator (?->), which allows safe access to object properties and methods without explicitly checking for null....
🌐
GitHub
github.com › php › php-src › issues › 8520
Array key evaluation on a null type · Issue #8520 · php/php-src
May 9, 2022 - <?php function evalKey() {throw new Exception();} var_dump(null[evalKey()] ?? 'default'); Now, in the context of using the null-coalescing operator one can expect this to lead to the right-hand-side of the operator being outputted without concerns ...
Published   May 09, 2022
🌐
Derick Rethans
derickrethans.nl › phpinternalsnews-65.html
PHP Internals News: Episode 65: Null safe operator — Derick Rethans
So you could do something like null safe operator bar equals foo, effectively assigning the string foo something that might or might not be null. I only learnt this recently. You can also foreach over an array into the property of an object, which I've never seen before in my 20 odd years writing PHP...
🌐
Reddit
reddit.com › r/php › should nullsafe operator (?->) emit "undefined variable/array key" warning unlike null coalescing operator (??)
r/PHP on Reddit: Should Nullsafe Operator (?->) emit "Undefined variable/array key" warning unlike null coalescing operator (??)
August 15, 2020 -

Sorry if I missed it from previous discussions, but while playing with PHP 8.0 beta1, I've found that usage of nullsafe operator (?->) on undefined variable or array key or object property does emit PHP warning.

As null coalescing operator (??) suppress similar kind of warnings, I though ?-> would work the same. Can I know any reason behind this? Only thing I can guess that it helps us to debug that which one is null value in long chain.

$object?->invalid?->property?->nonexistent?->method();

PHP warning will report if any property of this chain does not exists. But the same can be said for ?? one. Then?

https://3v4l.org/bjdCu

Thank You.

🌐
Medium
timjwilliams.medium.com › php8s-nullsafe-operator-or-optional-chaining-d0ea749ee641
PHP8’s Nullsafe Operator or “Optional Chaining” | by Tim Williams | Medium
April 26, 2023 - In this example, the static method ... calls. PHP 8’s nullsafe operator offers a clean and efficient way to handle null values when accessing object properties and calling methods....