Use &
:
foreach($arr as &$value) {
$value = $newVal;
}
&
passes a value of the array as a reference and does not create a new instance of the variable. Thus if you change the reference the original value will change.
PHP documentation for Passing by Reference
Edit 2018
This answer seems to be favored by a lot of people on the internet, which is why I decided to add more information and words of caution.
While pass by reference in foreach
(or functions) is a clean and short solution, for many beginners this might be a dangerous pitfall.
Loops in PHP don't have their own scope. - @Mark Amery
This could be a serious problem when the variables are being reused in the same scope. Another SO question nicely illustrates why that might be a problem.
As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior. - PHP docs for foreach.
Unsetting a record or changing the hash value (the key) during the iteration on the same loop could lead to potentially unexpected behaviors in PHP < 7. The issue gets even more complicated when the array itself is a reference.
Foreach performance.
In general, PHP prefers pass by value due to the copy-on-write feature. It means that internally PHP will not create duplicate data unless the copy of it needs to be changed. It is debatable whether pass by reference in foreach
would offer a performance improvement. As it is always the case, you need to test your specific scenario and determine which option uses less memory and CPU time. For more information see the SO post linked below by NikiC.
Code readability.
Creating references in PHP is something that quickly gets out of hand. If you are a novice and don't have full control of what you are doing, it is best to stay away from references. For more information about &
operator take a look at this guide: Reference — What does this symbol mean in PHP?
For those who want to learn more about this part of PHP language: PHP References Explained
A very nice technical explanation by @NikiC of the internal logic of PHP foreach
loops:
How does PHP 'foreach' actually work?