How can references be used within a foreach loop in PHP to maintain changes to array values?
When using a foreach loop in PHP to iterate over an array, changes made to the current array element within the loop do not persist outside of the loop because foreach operates on a copy of the array. To maintain changes to array values, you can use references within the foreach loop by prefixing the $value variable with an ampersand (&). This allows you to directly modify the original array elements.
$array = [1, 2, 3, 4, 5];
foreach ($array as &$value) {
$value *= 2;
}
unset($value); // unset the reference to avoid potential conflicts
print_r($array);