trysis
trysis

Reputation: 8416

PHP - foreach loops - $arr and &$value as same variable

foreach($foo as &$bar) {
  //do something
}

This is the syntax for a foreach loop in PHP. Usually, $foo & $bar are different variables, but my question is can they be the same variable? I'm asking if PHP will let me, not whether it is possible to write the code like that. I know this would modify the variable inside the loop, and I'm not worried about that.

Upvotes: 2

Views: 1825

Answers (3)

Barmar
Barmar

Reputation: 781255

Yes, it works. When a foreach loop starts, it makes a snapshot of the array contents. Then the iteration variable is successively assigned to the elements of that snapshot.

$foo = array(1, 2, 3);
foreach ($foo as &$foo) {
  echo "foreach: $foo\n";
}
echo "vardump: ";
var_dump($foo);

Outputs:

foreach: 1
foreach: 2
foreach: 3
vardump: int(3)

Upvotes: 2

Marc B
Marc B

Reputation: 360722

It will work, ONCE, but only because of a quirk in PHP:

php > $x = array(1,2,3);
php > foreach($x as $x) { echo $x; }
123
php > var_dump($x);
int(3)

Note that the loop actually ran for all 3 values of the original $x array, but after the loop exits, $x, is now a mere int - it's no longer an array.

This holds true if the as $x is a straight plain $x variable, or a &$x reference.

Upvotes: 2

federicot
federicot

Reputation: 12341

No, they cannot be the same variable; $foo would be an array and &$bar would be the reference to an element of that array. That's why it's called a for-each loop, because it's looping through the elements of an array and, in this case, modifying them directly (because you are using references).

Upvotes: 0

Related Questions