Problem/Motivation

When a reference is used in a foreach loop instead of using a simple variable, the reference remains assigned and keeps its "value" which is a reference, even after the foreach execution. Most of the time, this is not what the developer is expecting and the reference may be used wrongly in the rest of the code. For this reason, it is recommended to always unset a reference that is used in a foreach to avoid any unexpected side effects. Make sure that the referenced value variable is unset after the loop.

File: webform/src/WebformHelpManager.php

2353:    // Initialize help.
    foreach ($help as $id => &$help_info) {
      $help_info += [
        'id' => $id,
        'reset_version' => FALSE,
      ];
    }

Steps to reproduce

Test program:
<?php
$help = ['A' => 'b', 'C' => 'd'];
print_r($help);
foreach ($help as $id => &$help_info) {
        $help_info = [ 'id' => $id ];
}
print_r($help);
$i=0;
foreach ($help as $id => $help_info) {
        $i++;
}
print_r($help);
?>

The output is as follows:
Array
(
    [A] => b
    [C] => d
)
Array
(
    [A] => Array
        (
            [id] => A
        )
    [C] => Array
        (
            [id] => C
        )
)
Array
(
    [A] => Array
        (
            [id] => A
        )
    [C] => Array
        (
            [id] => A   <===
        )
)

Proposed resolution

2353:    // Initialize help.
    foreach ($help as $id => &$help_info) {
      $help_info += [
        'id' => $id,
        'reset_version' => FALSE,
      ];
    }
    unset($help_info);

Comments

fnalb2 created an issue. See original summary.

jrockowitz’s picture

What about not using a reference

foreach (array_keys($help) as $id) {
  $help[$id] += [
    'id' => $id,
    'reset_version' => FALSE,
  ];
}
fnalb2’s picture

Yes, this variant should also work.

  • 7d3b650 committed on 6.1.x
    Issue #3322908: Make sure that the referenced value variable is unset...

  • 7d3b650 committed on 6.x
    Issue #3322908: Make sure that the referenced value variable is unset...

  • 7d3b650 committed on 6.2.x
    Issue #3322908: Make sure that the referenced value variable is unset...
jrockowitz’s picture

Status: Active » Fixed

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.