Why is modifying array elements by reference inside foreach ($items as &$item) dangerous and how do you fix it?
❓ Interview Prompt: Explain the reference pointer mutation trap in foreach loops and why calling unset($item) immediately after the loop is mandatory.
In PHP, iterating over an array by reference ('foreach ($items as &$item)') allows mutating array elements directly without array indexing. However, it creates a infamous memory reference trap if not cleaned up.
The Reference Bug Trap:
When the loop finishes, the variable '$item' remains an active reference bound to the last element of the array in memory.
If you later execute another standard 'foreach ($items as $item)' loop using the same variable name '$item', PHP will overwrite the last element of your array on every iteration of the second loop, corrupting your data!
The Solution:
Always call 'unset($item);' immediately after finishing a reference 'foreach' loop to destroy the reference binding pointer.
Code Implementation Example
<?php
$numbers = [1, 2, 3];
// 1. Mutate elements in-place using reference &$num
foreach ($numbers as &$num) {
$num = $num * 10;
}
// DANGER: $num is STILL a reference pointing to $numbers[2]!
// FIX: Always unset reference immediately after loop!
unset($num);
// 2. Safe second loop after calling unset()
foreach ($numbers as $num) {
echo $num . "
";
}
// Outputs: 10, 20, 30Always call unset($item) immediately after a reference foreach ($arr as &$item) loop to prevent array data corruption in subsequent loops.