foreach() & references

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
EricS
Forum Contributor
Posts: 183
Joined: Thu Jul 11, 2002 12:02 am
Location: Atlanta, Ga

foreach() & references

Post 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?
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($selection as $key => $select)
{
  if($select == 1)
    $selection[$key] = 2;
}
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

or

Code: Select all

array_walk($selection, create_function('&$val, $index', 'if($val == 1) $val = 2;'));
EricS
Forum Contributor
Posts: 183
Joined: Thu Jul 11, 2002 12:02 am
Location: Atlanta, Ga

Post 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.
Post Reply