NYCPHP Meetup

NYPHP.org

[nycphp-talk] by ref or by val? for vs foreach + as

Adam Maccabee Trachtenberg adam at trachtenberg.com
Thu Jan 29 17:11:59 EST 2004


On Thu, 29 Jan 2004, Chris Bielanski wrote:

> It's clearly documented that foreach proxies the array being iterated. Does
> that behavior hold true when the array is passed in as a class member, ie
> foreach($foo->array as $bar)?

I believe it should work the same way, also operating on a copy of the array.

> I can't imagine it would act differently but I'm getting conflicted output
> in my own code.

I just dummied up a test and it works this way for me:

class foo {
  var $bar = array(1, 2, 3, 4, 5);
}

$f = new foo;

foreach($f->bar as $b) {
  print "$b\n";
  $b++;
}

foreach($f->bar as $b) {
  print "$b\n";
}

1
2
3
4
5
1
2
3
4
5

> So just to make sure I'm crystal clear on this..
>
> In a for loop (assume $i is the iterator and $array the array) one might
> assign to a local variable $foo = $array[$i]. At least I assume, based on
> doc and experience, that this is by-value. The by-ref operation would be
> $foo =& $array[$i], yes/no?

By value.

> With a foreach - foreach ($array as $foo) -  we are talking about
> *precisely* the same operation under differing syntax, yes/no?

Pretty much. In a for loop, you can modify the array inside the loop
and the changes will effect the loop. Inside an foreach, you're always
iterating through a copy of the array as it was when you entered the
iterator.

For instance, if you append new elements to $array, and you're looping
until $i < count($array), the loop will take this into account. If you
do that with a foreach, you won't iterate over the appended elements.

> and in both cases, $foo = 'bar' DOES NOT DO $array[$i] = 'bar', yes/no?

I would think not.

> and foreach(&$array as $foo) should be right out - it's only one value - the
> reference of $array, yes/no?

I've never tried this, but I'm willing to bet it won't give you a
by-reference iteration.

> I won't argue - this should be intuitive, but as I said, I'm getting
> conflicting output and I am not that good at writing up these questions!! :)

I try to simplify my code bit by bit until I reach the simplest case
possible that still reproduces the unexpected behavior. Then at least
you can post something understandable to a list for help when you
can't make heads nor tails of it. :)

-adam

-- 
adam at trachtenberg.com
author of o'reilly's php cookbook
avoid the holiday rush, buy your copy today!



More information about the talk mailing list