Skip to content

[Php72] Skip moved array pointer in WhileEachToForeachRector - #9017

Closed
TomasVotruba wants to merge 1 commit into
mainfrom
while-each-to-foreach-require-reset-pointer
Closed

TomasVotruba wants to merge 1 commit into
mainfrom
while-each-to-foreach-require-reset-pointer

Conversation

@TomasVotruba

@TomasVotruba TomasVotruba commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

while (list(...) = each($items)) continues from the array's internal pointer, while foreach always starts at the first item. The rewrite changed behaviour whenever the pointer was moved or read in the same scope:

next($items);
while (list(, $item) = each($items)) {} // skips the first item, the foreach does not

It also changed what current()/key() see after the loop, and a second while each() loop over the same array (which never runs, the pointer is at the end) started iterating again.

The rule now skips the loop when:

  • any other pointer function (current, pos, key, next, prev, end, reset, each) is called on the same variable in the function scope - a reset() right before the loop is fine
  • the variable is a by-reference parameter or closure use
  • the iterated expression is not a plain variable

Existing fixtures are unchanged; 5 skip_* fixtures cover the unsafe shapes. A pointer moved by the caller before entering the scope is not detectable and stays an accepted risk.

@TomasVotruba TomasVotruba changed the title [Php72] Skip while each() loop without reset pointer in WhileEachToForeachRector [Php72] Skip moved array pointer in WhileEachToForeachRector Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant