NYCPHP Meetup

NYPHP.org

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

Dan Cech dcech at phpwerx.net
Thu Jan 29 20:54:35 EST 2004


Adam Maccabee Trachtenberg wrote:

> On Thu, 29 Jan 2004, Chris Bielanski wrote:
>>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.

If you want to perform an operation on every member of an array using 
foreach, you can do:

foreach ( array_keys($array) as $key ) {
	$array[$key] =& myfunction($array[$key]);
}

As always there are any number of ways to skin a cat, if you just wanted 
to increment every member of an array you could do:

foreach ( $array as $key => $val ) {
	$array[$key]++;
}

which is equivalent to:

foreach ( array_keys($array) as $key ) {
	$array[$key]++;
}

Dan




More information about the talk mailing list