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.

Foreach in the PHP docs

2 thoughts on “PHP 4 foreach as references”

Leave a Reply to Nguyễn Quốc Quỳnh Khôi Cancel reply

Your email address will not be published. Required fields are marked *