What are some common pitfalls to avoid when using references in PHP foreach loops?

One common pitfall to avoid when using references in PHP foreach loops is modifying the array being iterated over within the loop. This can lead to unexpected behavior and errors. To avoid this, make a copy of the array before iterating over it if you need to modify it.

// Avoid modifying the array within the foreach loop
$array = [1, 2, 3, 4, 5];
foreach ($array as &$value) {
    $value *= 2;
}
unset($value); // unset the reference to avoid potential issues

// To avoid modifying the original array, make a copy before iterating
$array = [1, 2, 3, 4, 5];
$arrayCopy = $array; // make a copy of the original array
foreach ($arrayCopy as &$value) {
    $value *= 2;
}
unset($value); // unset the reference to avoid potential issues