can some one please explain the reference here? I know that reference is causing it to happen but how? why just in the index of 2? why not other ones?
I know what references does but in this particular example I am lost:
$a = array ('zero','one','two');
foreach ($a as &$v) {
}
foreach ($a as $v) {
}
print_r ($a);
output:
Array ( [0] => zero [1] => one [2] => one )
After the first foreach
loop, $v
will be a reference to the last element in $a
.
In the following loop $v
will be assigned to zero
then one
and then to itself (it is a reference). It's current value is now one
because of the previous assignment. That's why there are two one
's at the end.
For a better understanding: Your code is doing the same as the following lines:
// first loop
$v = &$a[0];
$v = &$a[1];
$v = &$a[2]; // now points to the last element in $a
// second loop ($v is a reference. The last element changes on every step of loop!)
$v = $a[0]; // since $v is a reference the last element has now the value of the first -> zero
$v = $a[1]; // since $v is a reference the last element has now the value of the second last -> one
$v = $a[2]; // this just assigns one = one
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With