Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a null safe operator for accessing array data?

As far as I know, the null safe operator doesn't work on arrays. Is there another way to achieve the same effect with array chaining?

For example:

$array = [];

if (isset($array['a'])) {
    if (isset($array['a']['b'])) {
        // run
    }
}

becomes:

$array<null-safe-oprator>['a']<null-safe-operator>['b'];

Googling reveals nothing on the topic.

like image 992
Petar Vasilev Avatar asked Nov 17 '25 03:11

Petar Vasilev


1 Answers

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(...);
like image 173
mickmackusa Avatar answered Nov 19 '25 20:11

mickmackusa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!