Skip to content

[DangerousDowngrade PHP 7.3] List reference assignment inside foreach #4376

Description

@leoloso

Feature Request

This is the continuation from #4315 and #4371, to downgrade the list reference assignment inside a foreach:

$array = [[1, 2], [3, 4]];
foreach ($array as list(&$a, $b)) {
    $a = 7;
}
var_dump($array);
/*
array(2) {
  [0]=>
  array(2) {
    [0]=>
    int(7)
    [1]=>
    int(2)
  }
  [1]=>
  array(2) {
    [0]=>
    &int(7)
    [1]=>
    int(4)
  }
}
*/

According to the RFC this is not downgradable:

The predominant advantage of adding support for this is that it allows you to use reference assignment for multiple variables at once, which is not currently possible. [...] the advantage here is that you can reference assign some, but not all of the variables in list().

After running this PHP code, the reference exists on $array[1][0] since $a is still in scope after the foreach(). This part cannot be reproduced in PHP 7.2

If we didn't care about the references, but only about the final values, this is doable:

$array = [[1, 2], [3, 4]];
foreach ($array as &$item) {
    $item[0] = 7;
}
var_dump($array);
/*
array(2) {
  [0]=>
  array(2) {
    [0]=>
    int(7)
    [1]=>
    int(2)
  }
  [1]=>
  &array(2) {
    [0]=>
    int(7)
    [1]=>
    int(4)
  }
}
*/

Notice how the reference at the end points to the 2nd item in the array, and not to the 1st element of that item.

Hence, the final references cannot be recreated, but the values can.

Suggestion

Create a new set DANGEROUS_DOWNGRADE_PHP73, and call this rule DangerousDowngradeListReferenceAssignmentInsideForeachRector

Diff

$array = [[1, 2], [3, 4]];
-foreach ($array as list(&$a, $b)) {
-    $a = 7;
+foreach ($array as &$item) {
+    $item[0] = 7;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions