Skip to content

Unsetting a nested array key makes PHPStan believe the parent array exists #7292

@derrabus

Description

@derrabus

Bug report

Unsetting a nested array key works even if the parent array key does not exist: unset($arr['foo']['bar']);. However, in the snippet below, PHPStan seems to assume that this operation would create that key. The error is:

Offset class-string on array<class-string, array<string, mixed>> in isset() always exists and is not nullable.

If I remove the first unset() operation, the error is gone. The error first appeared after upgrading from PHPStan 1.6 to 1.7.

Code snippet that reproduces the problem

class MyMetadata {
	/** @var class-string */
	public string $fqcn;
}

class MyClass {
    /** @var array<class-string, array<string, mixed>> */
    private $myMap = [];
	
    public function doSomething(MyMetadata $class): void
    {
        unset($this->myMap[$class->fqcn]['foo']);

        if (isset($this->myMap[$class->fqcn]) && ! $this->myMap[$class->fqcn]) {
            unset($this->myMap[$class->fqcn]);
        }
    }
}

https://phpstan.org/r/678ba358-f243-4786-9e77-e788138f28d6

Expected output

The code should pass without errors.

Did PHPStan help you today? Did it make you happy in any way?

PHPStan makes my everyday life as a developer easier. Thank you for this awesome tool. ❤️

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions