Skip to content

false positive: Variable $variableDefinedWithinForeach might not be defined. #651

@stesie

Description

@stesie

PHPStan since 0.9 doesn't detect early continue of foreach loop wih continue 2 in foreach/switch loop

Demo: https://phpstan.org/r/62fe427842b4f0c162961a5eaf75a158

<?php declare(strict_types = 1);

foreach (['foo', 'bar'] as $loopValue) {
        switch ($loopValue) {
        case 'foo':
                continue 2;

        case 'bar':
                $variableDefinedWithinForeach = 23;
                break;

        default:
                throw new \LogicException();
        }

        echo $variableDefinedWithinForeach;
}

The echo statement is actually only reachable via "bar"-case and there the variable in question is defined. PHPStan doesn't consider that continue 2 breaks the loop early and considers the variable undefined, hence triggering "might not be defined"

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions