Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
HonzaMatosik opened this issue Aug 2, 2022 · 4 comments · Fixed by phpstan/phpstan-src#1582

Comments

@HonzaMatosik
Copy link

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.

@staabm
Copy link
Contributor

staabm commented Aug 2, 2022

Oh wow. Never considerd writing code like that. feels too magic for my feelings.

Is this just a theoretical problem, or do you really have it like that?

if you write explicitly what you want todo it works like expected https://phpstan.org/r/276f7192-826b-431b-97bc-bf3babbe8e24

@herndlm
Copy link
Contributor

herndlm commented Aug 2, 2022

TIL: loops can assign array offsets :O

update: look at that, while we're surprised by the magic here, @rvanvelzen is already fixing it. impressive! ;)

@HonzaMatosik
Copy link
Author

HonzaMatosik commented Aug 2, 2022

@staabm

Oh wow. Never considerd writing code like that. feels too magic for my feelings.

I totally agree. 😅

Is this just a theoretical problem, or do you really have it like that?

It's more of a practical problem, but it isn't blocking as multiple workarounds works. Specifically I'm writing phpstan extension for Twig, and this is basically how Twig foreach loop looks after compilation.

@github-actions
Copy link

github-actions bot commented Sep 3, 2022

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Sep 3, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants