Skip to content

Missed change of variable type in foreach #4907

@integer

Description

@integer

Bug report

You iterate an array and overrides variable outside cycle. PHPStan not update variable type and expecting different type than real PHP runtime. Code falls with TypeError

Code snippet that reproduces the problem

function sayHello(): void
{
	$foo = [5,6,7];
	foreach ($foo as $i => $foo) {
		// ...			
	}
	// here is $foo int not array.
	bar($foo);  // TypeError: Argument 1 passed to bar() must be of the type array, integer given
}
	
/**
 * @param int[] $x
 * @return int[]
 */
function bar(array $x): array {
	return $x;
}
	
sayHello();

Same code here: https://phpstan.org/r/9743d6e1-0f56-4748-a50d-a61a0d79e6c2

Expected output

Parameter #1 $x of function bar expects array, int given.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions