PHP 4 foreach as references
PHP 4 doesn’t seem to create references for objects in foreach loops. e.g. the following will not change the original objects:
foreach($placeholder as $contentBlock) { $contentBlock->setPosition(1); }
The value of the position property in the original object will remain unaffected. This is quite rubbish. To get round it you need to get all the array keys and then create a separate variable to store a reference to the object you want to change:
foreach($placeholder as $key => $value) { $contentBlock =& $placeholder[$key]; $contentBlock->setPosition(1); }
The variable $value isn’t used at all but if you’re stuck using PHP 4 then this is the best you can do. Luckily PHP 5 works much more sensibly, but we don’t always get a chance to use that so I’m stuck with this slightly messy alternative.
2 Replies to “PHP 4 foreach as references”
Hey, let try:foreach ($array as $key => &$value){ // change your $value}
Not for PHP4, this only works in PHP5 and later