1

I have code with two foreach, first with &, second without:

$a = array(1, 2);

foreach ( $a as &$v ) {
    $v *= 1;
}

print_r($a); // output: array(1, 2)

$b = array();

foreach ( $a as $v ) {
    $b[] = $v;
}

print_r($b); // output: array(1, 1)

Why in second foreach $v always = 1 and array b is (1, 1) instead (1, 2)?

6
  • Try print_r($a)? What does it show? Commented Jul 4, 2017 at 17:15
  • 1
    Because $v is a reference to guess what? Commented Jul 4, 2017 at 17:16
  • $v is the address location. Commented Jul 4, 2017 at 17:16
  • 3
    Read warning here php.net/manual/en/control-structures.foreach.php Commented Jul 4, 2017 at 17:16
  • @u_mulder Thanks Commented Jul 4, 2017 at 17:23

1 Answer 1

1

You are changing the value of $a[1] in the first loop of the second foreach, if you do a var_dump instead, you get output that indicates it is a reference:

array(2) {
  [0]=>
  int(1)
  [1]=>
  &int(2)
}

So, on the second foreach $a[1] (which is actually &$v; becomes 1), which then is the second value that comes out of $a in the loop, because it is actually:

$a[
   1,
   &$v
];

If you were to reassign $v after the loop, you would get the new value in the array instead:

<?php

$a = [1, 2];
foreach ( $a as &$v ) {
    $v = $v;
}
var_dump($a); // output: array(int(1), &int(2))
$b = [];
foreach ( $a as $v ) {
    $b[] = $v;
}
$v = 3;
var_dump($a); // output: array(int(1), &int(3))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.