Reputation: 308
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)?
Upvotes: 1
Views: 76
Reputation: 10384
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))
Upvotes: 1