Page 1 of 1

Referential Foreach?

Posted: Wed May 31, 2006 11:52 am
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

Posted: Wed May 31, 2006 11:55 am
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.

Posted: Wed May 31, 2006 12:02 pm
by feyd

Code: Select all

foreach($array as $key => $value)
{
  $value =& $array[$key];
  // alter away
}

Posted: Wed May 31, 2006 4:25 pm
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'];
}