phparraysoptional-chaining

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.


Solution

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

    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.

    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.

    So ultimately, don't use the null-safe operator unless you have methods in your chain. You'll never need to worry about making a null-safe "chain" with an array because arrays do not offer such functionality to chain functions/methods in that fashion.