Referential Foreach?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
TheMoose
Forum Contributor
Posts: 351
Joined: Tue May 23, 2006 10:42 am

Referential Foreach?

Post by TheMoose »

Not sure if this is PHP Theory or not, but is there such a thing as a referential foreach loop? What I mean is, when I do a foreach loop, currently (at least for PHP4) it accesses the 'each' item as a copy, and not a reference. I know PHP5 you can do something like:

Code: Select all

foreach($array as &$item) {
   // whatever
}
You can then assign values to anything that might potentially be in item, and it will update the parent array, whereas in PHP4, you can't even do the above (take out the ampersand). But with this, you can't do something like:

Code: Select all

foreach($array as $item) {
    $item['total'] = $item['count'] * $item['price'];
}
It will "work", as $item['total'] can be used within that loop to access that calculated value, but I want to be able to access a calculated value later on. Is there an easy workaround to this, or should I just stick to my for($i=0) loops?

Thanks
- Moose
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Post by infolock »

As far as I know, php < 5.0 does not support this type of thing. I as well have the same issues where I'm looping through an array, and need to change the value of the key..

as per your example, that is the only alternative method I know of, and that is explicitly defining the key in the array to have another value.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

foreach($array as $key => $value)
{
  $value =& $array[$key];
  // alter away
}
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

Or

Code: Select all

foreach(array_keys($array) as $key) {
    $array[$key]['total'] = $array[$key]['count'] * $array[$key]['price'];
}
Or

Code: Select all

foreach($array as $key => $item) {
    $array[$key]['total'] = $item['count'] * $item['price'];
}
(#10850)
Post Reply