Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reference and arrays that can happen unexpectedly

Tags:

arrays

php

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 )
like image 854
Nickool Avatar asked Sep 30 '22 01:09

Nickool


1 Answers

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
like image 185
hek2mgl Avatar answered Oct 13 '22 01:10

hek2mgl