Skip to content

Incorrect behavior of ForeachItemsAssignToEmptyArrayToAssignRector #9587

@solverat

Description

@solverat

Bug Report

Subject Details
Rector version last dev-main
Installed as composer dependency

Minimal PHP Code Causing Issue

See https://getrector.com/demo/26d774ef-4a09-4b47-8f8f-47d7f77ab9c1

<?php

final class DemoFile
{
    public function run(): JsonResponse
    {
        $thumbnails = [];
        $groups = [];
        $list = new DemoList();
        foreach ($list->getItems() as $item) {
            if ($item->hasGroup()) {
                $groups[] =['id' => $item->getName()];
            } else {
                $thumbnails[] = ['id' => $item->getName()];
            }
        }

        foreach ($groups as $group) {
            $thumbnails[] = $group;
        }
        
        return $this->adminJson($thumbnails);
    }
}

Responsible rules

  • ForeachItemsAssignToEmptyArrayToAssignRector

Expected Behavior

Keep the iteration that enriches the existing array instead of resetting it.

foreach ($groups as $group) {
     $thumbnails[] = $group;
}

I know this is a bit of a silly example, it's just meant to show the problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions