How can one avoid overwriting array elements while using foreach loop in PHP?

When using a foreach loop in PHP, it is important to remember that the loop operates on a copy of the array elements, not the actual elements themselves. This means that modifying the array element within the loop will not affect the original array. To avoid overwriting array elements, you can use a reference variable within the foreach loop to directly modify the original array elements.

$array = [1, 2, 3, 4, 5];
foreach ($array as &$value) {
    $value *= 2;
}
unset($value); // unset the reference variable
print_r($array); // Output: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )