The PHP Foreach Ended. Why Did the Last Array Element Change?

A PHP foreach reference can survive the loop. Trace how a later value loop overwrites the last array element, and end the binding before reusing the variable.

Share
Orange array blocks connected by looping cables, with an assignment stylus beside the final block on charcoal.

The last item in your PHP array has quietly turned into a copy of the one before it. The array still has the right length. The mutation loop finished. Then a second loop, with an empty body, somehow made things worse.

Check whether the first loop used foreach ($values as &$value). PHP can leave $value bound to the last array element after the loop ends. Reusing that variable in a later assignment, including a by-value foreach, writes through the old reference. Put unset($value) immediately after the by-reference loop to break the binding. The PHP foreach manual explicitly documents this trap.

This is an AI-prepared, documentation-based explainer, not a personally reproduced incident. All code, traces and expected outcomes below are illustrative and unexecuted. See the editorial policy.

The empty loop body is a useful clue

Let's use three integers so there's nowhere for the explanation to hide:

$values = [10, 20, 30];

foreach ($values as &$value) {
    $value += 1;
}

foreach ($values as $value) {
    // No application code here.
}

The first loop's intended result is [11, 21, 31]. Applying the documented reference behavior to the second loop predicts [11, 21, 21]. That prediction is a trace of the language rules, not output captured from a PHP process.

It's tempting to clear the second loop because its body doesn't write anything. But foreach itself assigns each visited value to its loop variable. The body is empty; the assignment machinery is very much at work. An empty body isn't an alibi.

The first loop gave $value another job: it became an alias for an array element. At the end of this nonempty loop, that element is $values[2]. Leaving the braces doesn't release the alias.

Follow the destination of each assignment

Before blaming the arithmetic, separate the value being read from the location being written. Here is the illustrative second pass:

IterationValue readAssignment destinationArray afterward
First11 from index 0$value still aliases index 2[11, 21, 11]
Second21 from index 1The same index 2[11, 21, 21]
Third21 from the now-changed index 2The same index 2[11, 21, 21]

The disappearing 31 is the revealing clue. It was already overwritten by the time iteration reached its slot. Repeating the previous value at the end is a consequence of the assignment destination staying attached, rather than evidence that foreach randomly skipped the last item.

The later loop doesn't need an ampersand to trigger this. Removing the ampersand from that later syntax doesn't undo the reference created earlier. PHP's reference explanation describes references as names sharing the same content. When diagnosing this, ask what a variable is still bound to, as well as what value it appears to hold.

Break the binding where its job ends

The smallest repair keeps the intended in-place update and ends the alias immediately afterward:

$values = [10, 20, 30];

foreach ($values as &$value) {
    $value += 1;
}
unset($value);

foreach ($values as $value) {
    // Ordinary value iteration now.
}

For this fresh-array illustration, the expected final values stay [11, 21, 31]. The manual on unsetting references explains why: unset breaks the binding between the variable name and its content. Unsetting the loop variable doesn't delete the last array element.

Place that cleanup beside the loop that creates the reference. If it sits three screens later, the next developer has to discover the invisible attachment before safely reusing a perfectly ordinary variable name. That's a generous amount of suspense for a variable called value.

Using a different variable in the next loop can avoid this particular overwrite. It still leaves the original alias available for a later assignment. Ending the reference's lifetime addresses the cause more directly than relying on everybody remembering which variable name is haunted.

If you don't need an alias, don't leave one behind

For a simple scalar transformation, writing through an explicit key can make the destination easier to see. This alternative starts with a fresh array and a fresh, non-reference loop variable:

$values = [10, 20, 30];

foreach ($values as $key => $number) {
    $values[$key] = $number + 1;
}

Here the mutation is visible at $values[$key], and this loop doesn't create a by-reference loop-variable binding. This isn't a universal rewrite for every iterable or algorithm. If earlier code has already bound a variable by reference, changing a later loop's spelling doesn't clean up that earlier binding.

The diagnosis also has limits. A wrong last value alone doesn't prove a lingering foreach reference. Check the actual code path for the earlier by-reference binding and later reuse. Other writes, nested references and application logic still deserve inspection. The trace above deliberately uses a nonempty flat scalar array and normal completion; it doesn't claim to cover every reference arrangement or early-exit path.

Keep the observation step from changing the evidence

This matters during debugging because adding a loop to inspect values can reuse the very variable that carries the alias. A diagnostic pass can become the mutation you're trying to explain. At a breakpoint, inspect the array directly before and after the suspect assignment, and check the earlier loop's ampersand and cleanup. Treat a new inspection loop as executable code with assignments of its own.

For a proposed regression check, use distinct final values so a copied neighbor is obvious. Check the complete array immediately after transformation, then again after the later iteration or variable reuse that used to corrupt it. Include a later assignment using values from a different array if that happens in the real function. Checking only the count won't catch an overwrite that leaves every key in place. These are suggested checks, not tests run for this article.

If the symptom is changing numeric keys during a merge, the separate array_merge key-renumbering investigation follows a different mechanism. More related investigations are in the PHP archive.

On the next review of a by-reference foreach, look one line beyond its closing brace. Make the end of that binding visible there, before another innocent-looking assignment gets a vote in the last element's future.