You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
foreach narrowing the key variable writes the PHPDoc key type into the iterated array's native type (false function.impossibleType with treatPhpDocTypesAsCertain: false) #15250
When a foreach body narrows the key variable (for example it throws for some keys), PHPStan updates the iterated array's type after the loop to use the narrowed key type. The native type gets updated with the PHPDoc-derived key type. So the native type ends up claiming something only the PHPDoc says, and with treatPhpDocTypesAsCertain: false checks that should rely only on native types report errors:
/** * @param array<'a'|'b', int> $array */functiondoFoo(array$array): void
{
\PHPStan\dumpNativeType($array); // arrayforeach ($arrayas$key => $value) {
if ($key === 'a') {
thrownew \LogicException();
}
}
\PHPStan\dumpNativeType($array); // expected: array, actual: array<'b', mixed>foreach ($arrayas$key => $value) {
if (is_int($key)) { // with treatPhpDocTypesAsCertain: false this must not be reportedecho$key;
}
}
}
Actual output (level 8, treatPhpDocTypesAsCertain: false):
8: Dumped type: array
14: Dumped type: array<'b', mixed>
17: Call to function is_int() with 'b' will always evaluate to false. [function.impossibleType]
The native type of $array is just array, and nothing in native code rules out int keys. Without the first loop, the is_int() call isn't reported with treatPhpDocTypesAsCertain: false. With treatPhpDocTypesAsCertain: true it's reported with the tip "Because the type is coming from a PHPDoc...". After the first loop, the tip disappears and the error stays even in loose mode, because the native type now contains the PHPDoc key 'b'.
Cause: in src/Analyser/StmtHandler/ForeachHandler.php (the block that rewrites the iteratee type after the loop), the native key types are read from the scope that treats PHPDoc types as certain. Line 393 is identical to the PHPDoc line above it:
The union of $keyLoopNativeTypes is then applied with $newExprNativeType->mapKeyType(...) (line 434), and the result goes into assignVariable()/assignExpression() as the native type. The value side of the same loop already does it right: $dimFetchNativeType and $valueVarNativeType are read from $scopeWithIterableValueType->doNotTreatPhpDocTypesAsCertain().
The second dumpNativeType($array) should print array, and there should be no function.impossibleType error on line 17 when treatPhpDocTypesAsCertain is false.
Activity
phpstan-bot commentedon Sep 17, 2026
Closed via merging phpstan/phpstan-src#6463
github-actions commentedon Oct 19, 2026
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.