CKTIS / PHP
PHP: foreach by reference and by value
Use `&$value` to update array elements in place, and learn why `unset($value)` prevents a later loop from accidentally overwriting the last element.
Version: PHP 8.3
Syntax
foreach ($items as $value) { /* ... */ }
foreach ($items as $key => $value) { /* ... */ }
foreach ($items as &$value) { /* ... */ }
unset($value);
foreach ($items as $key => &$value) { /* ... */ }
unset($value);foreach ($items as $value) assigns the current value to $value on each iteration. If $value is not already a reference, assigning a different value to it does not replace the array element. This is not a deep copy: if the element holds an object, changing a property through $value affects that same object.
The phrase foreach reference &$value refers to the form foreach ($items as &$value). The & makes $value an alias for the current element, so assigning to $value updates the element itself. The optional $key => &$value form also assigns the key to $key, but does not bind the key by reference.
Once a by-reference loop that ran at least one iteration exits, $value still refers to the last element visited. Put unset($value) immediately after the loop: it removes the variable binding, not the array element. Otherwise, a later by-value foreach that reuses the same variable can overwrite that element even with an empty loop body.
Examples
<?php
function demo(bool $detach): string
{
$items = [1, 2, 3];
foreach ($items as &$value) {
$value *= 2;
}
if ($detach) {
unset($value);
}
foreach ($items as $value) {
// The assignment to $value happens even with an empty body.
}
return implode(', ', $items);
}
echo 'Without unset: ', demo(false), "\n";
echo 'With unset: ', demo(true), "\n";
Result
Without unset: 2, 4, 4 With unset: 2, 4, 6
Both calls double the numbers. In the first call, the second loop changes the last element from `6` to `4`. In the second call, `unset($value)` breaks the binding before the second loop, so `6` stays unchanged.
Related lessons
- PHP · Lesson 80 · Advanced · Version: 2