PHP foreach loops pass arrays by value
December 17th, 2006 | Filed under PHP, Code snippetsI nearly lost my mind debugging a problem with some PHP I’d written awhile back that wasn’t working as I’d expected on one server (but fine on my own.)
After many hours of cursing myself for not having a better debugging system, I discovered it was a PHP 4 versus PHP 5 code incompatibility. Turns out that PHP passes arrays into foreach loops by value, which means that any changes you make to that array inside the foreach don’t appear after the foreach, because it’s acting on a copy of the arrray instead of the original data.
So code like this:
Doesn’t print “nothingnothing”, which is what I’d expect; it prints “rainbowspuppies.” In PHP4, apparently, there’s no way to get around this. In PHP5, you can pass the array into the foreach by reference using this notation: foreach ($gina->interests as & $interest)
For now, I to make my code both PHP4 and PHP5 compatible, I went with a:
while ($i=0; $i < sizeof($gina->interests); $i++)
Which just isn’t as readable as the foreach. Here’s the PHP doc on foreach (which clearly states the PHP 5 caveat.)