Unset a referenced foreach variable before reusing it
A loop updates each element by reference. Later, another loop uses the same variable name and the last item changes mysteriously. The variable remained a reference to the final array element after the first loop finished.
End the reference explicitly
<?php
$amounts = [10, 20, 30];
foreach ($amounts as &$amount) {
$amount *= 2;
}
unset($amount);
foreach ($amounts as $amount) {
// Read-only iteration after the reference has been removed.
}
assert($amounts === [20, 40, 60]);
unset($amount) removes the loop variable's reference binding; it does not remove the last element from $amounts. Without that step, later assignment to $amount can write through to the array.
Prefer a transformation when mutation is unnecessary
For a simple conversion, array_map returns a new array and avoids the lingering reference entirely. For a large in-place update, a reference loop may be intentional. Choose based on data size and clarity rather than assuming either form is always faster.
When diagnosing this class of bug, inspect code after the apparently correct transformation. The damaging assignment may be several lines later, including a logging loop that appears harmless. A local unit test should assert the entire resulting array, especially its last two elements.
References are also easy to retain in closures and object properties. Keep their scope small and name the reason for using them. If the only purpose is to save a short assignment, an explicit indexed update may make the behavior easier to maintain.
Reference
Official documentation. The examples here illustrate the stated boundary; adapt them to your application and test its failure paths.