Skip to content

Understand always-overwritten arrays in foreach#4534

Merged
ondrejmirtes merged 1 commit into2.1.xfrom
overwritten-arrays
Nov 7, 2025
Merged

Understand always-overwritten arrays in foreach#4534
ondrejmirtes merged 1 commit into2.1.xfrom
overwritten-arrays

Conversation

@ondrejmirtes
Copy link
Copy Markdown
Member

@ondrejmirtes ondrejmirtes commented Nov 7, 2025

I don't understand why I didn't do this years ago 😂

Closes phpstan/phpstan#2273
Closes phpstan/phpstan#13730

@ondrejmirtes ondrejmirtes merged commit 7738398 into 2.1.x Nov 7, 2025
331 of 345 checks passed
@ondrejmirtes ondrejmirtes deleted the overwritten-arrays branch November 7, 2025 20:35
&& !$continueExitPointHasUnoriginalKeyType
&& $stmt->keyVar !== null
&& $exprType->isArray()->yes()
&& $exprType->isConstantArray()->no()
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tbh I did not yet understand why this PR works, but I wonder whether we could use the same logic to also infer a better result when the iteratee is a known constant array?

like in

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this works - I look at $a[$k] type at the end of the loop and at each continue point and if some other conditions are true (like there are zero break points), I rewrite the whole array value type with the $a[$k] type unioned from all the points I looked at.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When $foreach->expr is a constant array I feel like we need a different approach, possibly analysing the foreach separately for each item (but run $nodeCallback for the rules still only once).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also I want to look at foreach ($a as &$v) to understand it better that also needs a different approach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

loop over all elements of array with coalesce operator should remove null False positive on arrays transformation with exceptions

2 participants