CKTIS / PHP
Iterating by reference with foreach and &$p
Use `&$p` to update array elements directly in a `foreach` loop. Call `unset($p)` afterward so a later assignment does not accidentally overwrite an array element.
Version: PHP 8.3
Syntax
foreach ($items as &$p) {
// Read or modify the current element through $p.
}
unset($p);
// With a key:
foreach ($items as $key => &$p) {
// $key receives the key; $p refers to the element's value.
}
unset($p);In PHP 8.3, foreach ($items as &$p) binds $p to the current array element on each iteration. Assigning to $p therefore updates the element itself. The & marks a reference: another name for the same value, not a pointer. In foreach ($items as $key => &$p), $key receives the key, and only the value is bound by reference.
By contrast, foreach ($items as $p) assigns each value to $p without binding it to the current element. If $p is not already a reference, a plain assignment to $p does not replace an array element.
After normal completion over a nonempty array, $p still refers to the last element. Call unset($p) immediately after the loop: it removes the binding, not the array element. Without it, even a later by-value loop that reuses $p without & can silently overwrite that last element each time it assigns to $p.
Examples
<?php
$items = [1, 2, 3];
foreach ($items as &$p) {
$p *= 2;
}
unset($p);
$sum = 0;
foreach ($items as $p) {
$sum += $p;
}
echo implode(', ', $items), "\n", $sum, "\n";
Result
2, 4, 6 12
The first loop doubles the elements. After `unset($p)`, the second loop sums them without changing the array. Remove only `unset($p);` and the expected lines become `2, 4, 4` and `10` instead of `2, 4, 6` and `12`.
Related lessons
- PHP · Lesson 20 · Advanced · Version: 2