Links and arrays that may happen unexpectedly

Can someone explain the link here? I know this link causes this, but how? why in index 2? why not others?

I know what links do, but in this particular example I get lost:

$a = array ('zero','one','two'); foreach ($a as &$v) { } foreach ($a as $v) { } print_r ($a); 

exit:

 Array ( [0] => zero [1] => one [2] => one ) 
+5
source share
1 answer

After the first loop, foreach $v will be a reference to the last element in $a .

In the next loop, $v will be assigned zero , then one , and then to itself (this is a link). This current value is now one due to a previous assignment. That is why there are two one at the end.

For a better understanding: your code performs the same actions 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 
+4
source

Source: https://habr.com/ru/post/1200436/


All Articles