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

Advertisements
This entry was posted in PHP, Programming. Bookmark the permalink.

2 Responses to PHP 4 foreach as references

  1. Hey, let try:foreach ($array as $key => &$value){ // change your $value}

  2. Anonymous says:

    Not for PHP4, this only works in PHP5 and later

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s