Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
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
Comment #2
jrockowitz CreditAttribution: jrockowitz as a volunteer and at Webform module Open Collective, The Big Blue House commentedWhat about not using a reference
Comment #3
fnalb2 CreditAttribution: fnalb2 commentedYes, this variant should also work.
Comment #7
jrockowitz CreditAttribution: jrockowitz as a volunteer and at Webform module Open Collective, The Big Blue House commented