QA
Beginner LevelPHP 8+

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
<?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, 30
💡Correct usage of foreach by-reference with unset() cleanup.
🎯 Interview Key Takeaway

Always call unset($item) immediately after a reference foreach ($arr as &$item) loop to prevent array data corruption in subsequent loops.

#foreach#References#Memory#Bugs#Beginner
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?