Learn why using unset($value); after a foreach loop in PHP is essential to prevent unexpected behavior. Understand how references work and how to safely modify array elements with examples.
When you use &$value
in a foreach
loop, like this:
foreach ($arr as &$value) {
$value = $value * 2;
}
PHP creates a reference to the array element, not a copy. After the loop ends, $value
still points to the last element of the array.
That means if you use $value
later in your code, you might accidentally change the last element of the array — even without realizing it.
unset($value);
<?php
$arr = [1, 2, 3];
foreach ($arr as &$value) {
// Doubles each element
$value *= 2;
}
// Oops! This modifies the last element again!
$value = 99;
print_r($arr);
?>
Output:
Array
(
[0] => 2
[1] => 4
[2] => 99 // ← unexpected!
)
unset($value);
<?php
$arr = [1, 2, 3];
foreach ($arr as &$value) {
$value *= 2;
}
unset($value); // break the reference
$value = 99; // Now this does NOT affect $arr
print_r($arr);
?>
Output:
Array
(
[0] => 2
[1] => 4
[2] => 6 // ← safe and expected
)
unset($value);
to break the lingering reference after a foreach
loop with &
.