Skip to content

For loop - Variable might not be defined even if it is defined #11218

Closed

Description

@JulienChavee

Bug report

Hello,

Following this test: https://phpstan.org/r/6ff7bf65-fcdc-4a07-8596-3cbee65338be
Phpstan reports the variable $test as undefined, but it is always defined.

If I try to initialize the $test variable outside the loop, I get the error "Offset 'test' does not exist on array{}" but again it always exists
https://phpstan.org/r/b6a3c5fc-a4d2-4525-915e-f392b32e5193

Is it something that can be fixed in phpstan?

Code snippet that reproduces the problem

No response

Expected output

Phpstan should not report the variable/offset as undefined

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

As always, phpstan helps us a lot, so thank you for all the good work made on this tool!

Activity

  1. ondrejmirtes commented on Jun 21, 2024

    @ondrejmirtes
    Member

    There are many ways how to rewrite this code so that PHPStan doesn't report an error: https://phpstan.org/r/073f7f16-e6d1-4f14-9c92-2fe0a925e123

    I agree this shouldn't be reported, but it's hard for static analyser to understand what's going on.

  2. phpstan-bot commented on Sep 23, 2024

    @phpstan-bot
    Contributor

    @JulienChavee After the latest push in 2.0.x, PHPStan now reports different result with your code snippet:

    @@ @@
    -11: Offset 'test' does not exist on array{}|array{test: literal-string&non-falsy-string}.
    +11: Offset 'test' might not exist on array{}|array{test: literal-string&non-falsy-string}.
    Full report
    Line Error
    11 `Offset 'test' might not exist on array{}
  3. deleted a comment from phpstan-bot on Mar 9, 2025
  4. phpstan-bot commented on Apr 13, 2026

    @phpstan-bot
    Contributor

    Closed via merging phpstan/phpstan-src#5386

  5. github-actions commented on May 15, 2026

    @github-actions

    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.

  6. locked as resolved and limited conversation to collaborators on May 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions