Page 1 of 1

foreach() & references

Posted: Wed Jun 23, 2004 11:51 am
by EricS
I need to run through an array with a foreach loop, but I need to value which is passed from the foreach iteration to be a reference so that when I make a change, it will stick.

Code: Select all

foreach($selection as $select) {
     if ($select == 1) {
          $select = 2;
     }
}
This is just an example. But when this foreach loop ends. Any value that was 1 is not changed to 2 because only a copy of the value of $selection was passed in, not a reference.

I've tried the following and only get parse errors:

Code: Select all

foreach($selection as &$select) {
     if ($select == 1) {
          $select = 2;
     }
}

Code: Select all

foreach(&$selection as $select) {
     if ($select == 1) {
          $select = 2;
     }
}
Any ideas?

Posted: Wed Jun 23, 2004 12:09 pm
by feyd

Code: Select all

foreach($selection as $key => $select)
{
  if($select == 1)
    $selection[$key] = 2;
}

Posted: Wed Jun 23, 2004 12:56 pm
by Weirdan
or

Code: Select all

array_walk($selection, create_function('&$val, $index', 'if($val == 1) $val = 2;'));

Posted: Wed Jun 23, 2004 1:10 pm
by EricS
feyd wrote:

Code: Select all

foreach($selection as $key => $select)
{
  if($select == 1)
    $selection[$key] = 2;
}
Still not passed as a reference.

To Weirden, thanks, I hadn't thought of using array_walk.

Anyways, after further research it appears that foreach can not be passed or pass references to arrays. If any one know different. Please let me know.

I ended up using a temporary array to store the contents as I iterated and then set the main array equal to the temp array.