Passing Values by Reference in PHP 5
Every other year or so, I go through the PHP manual. Often I do this in coordination with a book I’m about to write, like now, as I’m writing the
\[intlink id="3168" type="post"\]third edition of my “PHP 5 Advanced” book
\[/intlink\]. 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\]foreach ($array as $key => $value) { $array
\[$key\]= “some updated $value”; }
\[/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.
…
