Passing Values by Reference in PHP 5
. Generally, though, I’m a big advocate of re-reading manuals. It’s a great way to correct mistaken thinking you may have, and to learn new and better approaches. For example, I just came across something that had previously slipped past me: the ability to change an array within a foreach loop by passing values by reference.
In versions of PHP prior to 5, in order to change the values of array elements within a loop, you had to do this:
\[php\]\[$key\]\[/php\]Just changing the value of $value within that foreach loop had no impact on the actual array element, as the loop only received the value of each array element, not the actual element itself.
This doesn’t come up often—if I need to change the elements in an array, I’m likely to use array_walk(), but it’s nice to know that in PHP 5 you can pass array values by reference in a foreach loop, so that changing the value within the loop actually changes the array:
…