Skip to content

while-true-if-break: Variable might not be defined #11545

Closed

Description

@donquixote

Bug report

If a loop has no exit condition in the regular place, but a custom exit condition with if()..break, then phpstan fails to see a variable as defined that is defined inside the exit condition conditional block.

Similar to:

This problem might have the same technical cause, but it is a different test case, and hence it deserves its own issue - I think.

Code snippet that reproduces the problem

https://phpstan.org/r/1b3c4c9e-643a-4a50-90a9-875ad27af465

function foo(int $max): void {
	$i = 0;
	while (true) {
		if ($i > $max) {
			$result = 'done';
			break;
		}
		++$i;
	}
	print $result;  // Variable $result might not be defined.
}

Expected output

No inspection warning.

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

No response

Activity

  1. added this to the Easy fixes milestone on Aug 22, 2024
  2. MacGritsch commented on Jan 5, 2025

    @MacGritsch
  3. VincentLanglet commented on Mar 2, 2026

    @VincentLanglet
    Contributor

    Same issue with foreach

    phpstan.org/r/00f146fe-cca5-4dc7-8677-20546a68386e

    Just remove strict-rules option
    https://phpstan.org/r/2e89a4eb-02a0-49be-8cd0-bcdb160bdd97

    Same for the for Loop.

    It's about the polluteScopeWithLoopInitialAssignments and polluteScopeWithAlwaysIterableForeach options.

    Other cases will be handled by phpstan/phpstan-src#5118

  4. phpstan-bot commented on Mar 3, 2026

    @phpstan-bot
    Contributor

    Closed via merging phpstan/phpstan-src#5118

  5. github-actions commented on Apr 4, 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 Apr 4, 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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions