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:
foreach ($array as $key => $value) { $array[$key] = "some updated $value"; }
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:
foreach ($array as &$value) { $value = "some updated $value"; }
As you can see there, prefacing $value by & means that the variable is passed by reference, not by value, just as you’d have in a function parameter.
Again, perhaps this isn’t a life changing thing to learn (okay, it isn’t), but it’s interesting to know. As I continue to work my way through the PHP manual (again!), I’ll continue to share interesting little tidbits I’m finding, or discovering anew.