Make sure that the referenced value variable is unset after the loop

Created on 20 July 2023, 11 months ago
Updated 7 August 2023, 11 months ago

Using sonarqube to review out code we have this "crital" warning:

"Make sure that the referenced value variable is unset after the loop"

In advagg.admin.inc file, line 1088

  foreach ($element_info as $type => &$values) {
    $output .= $type . ":\n";
    foreach ($values as $key => &$value) {
      if ($key === '#items' || $key === '#type') {
        continue;
      }
      if (empty($value)) {
        $output .= '  ' . $key . ' - ' . str_replace(array("\r", "\n"), '', (string) var_export($value, TRUE)) . "\n";
      }
      elseif (is_array($value)) {
        $output .= '  ' . $key . ' - ' . implode(', ', $value) . "\n";
      }
      else {
        $output .= '  ' . $key . ' - ' . print_r($value, TRUE) . "\n";
      }
    }
  }

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.

Noncompliant Code Example

$arr = array(1, 2, 3);
foreach ($arr as &$value) { // Noncompliant; $value is still alive after the loop and references the last item of the array: $arr[2]
    $value = $value * 2;
}
$value = 'x';
Compliant Solution
$arr = array(1, 2, 3);
foreach ($arr as &$value) { // Compliant; there is no risk to use by mistake the content of $value pointing to $arr[2]
    $value = $value * 2;
}
unset($value);
$value = 'x';
πŸ› Bug report
Status

Fixed

Version

2.36

Component

Code

Created by

πŸ‡ͺπŸ‡ΈSpain Carlitus

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.69.0 2024