Skip to content

False positive on non existing array offset if array is used as foreach key #7737

@HonzaMatosik

Description

@HonzaMatosik

Bug report

If array is used as foreach key, phpstan reports $context["_key"] as non existing offset, but it is defined (tested on PHP 8.1).

Also related: Offset can exist (if $context["value"] is not empty) outside of forech scope, so calling unset should be safe.

Code snippet that reproduces the problem

<?php declare(strict_types = 1);

$context = [
    'values' => [1, 2, 3],
];
foreach ($context['values'] as $context["_key"] => $context["value"]) {
    echo sprintf("Key: %s, Value: %s\n", $context["_key"], $context["value"]);
}

unset($context["_key"]);

https://phpstan.org/r/6a63cb67-ecf7-484b-87b3-283595ddd3ef

Expected output

No errors

Did PHPStan help you today?

Yes! It makes my code safer and more reliable every day since 2016.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions