Larry Ullman

Translating Geek Into English

Passing Values by Reference in PHP 5

2 mins to read
\[intlink id="3168" type="post"\]\[/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\]\[$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:

\[php\]\[/php\]

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.