Questions about php foreach reference
typecho
typecho 2017-07-04 13:45:55
0
3
854

Foreach uses & to traverse the array arr2, and then traverses the array again. The result obtained is very confusing. I wonder if any expert can explain how the & traversal pointer moves.
code show as below:

    $arr2 = ['a','s','d'];
    foreach ($arr2 as $k => &$v){
        echo $k." ".$v."<br>";
    }
    //unset($v);
    foreach ($arr2 as $k => $v){
        echo $k." ";
        echo $v." ".current($arr2)."<br>";
    }

Result:
0 a
1 s
2 d
0 a a
1 s a
2 s a

Why does the pointer stop when it moves to s during the second traversal?

typecho
typecho

Following the voice in heart.

reply all(3)
迷茫

Or you can do this:

<?php

$arr2 = ['a','s','d'];

foreach ($arr2 as $k => &$v){
    echo $k." ".$v.PHP_EOL;
}

while(current($arr2)) {
    echo key($arr2).'->'.current($arr2).PHP_EOL;
    next($arr2);
}

Output:

0 a
1 s
2 d
0->a
1->s
2->d
phpcn_u1582

One more thing

foreach()循环对数组内部指针不再起作用,在PHP7之前,当数组通过foreach迭代时,数组指针会移动。
    现在开始,不再如此,见下面代码。。
$array = [0, 1, 2];
foreach ($array as &$val) 
{
var_dump(current($array));
}
PHP5运行的结果会打印int(1) int(2) bool(false)
PHP7运行的结果会打印三次int(0),也就是说数组的内部指针并没有改变。
之前运行的结果会打印int(1), int(2)和bool(false)
我想大声告诉你

Reason:

  • In the first foreach, the pass by reference method is adopted. The first loop $v points to the storage space of $arr2[0], and the second time points to > $arr2[ 1] storage space, the end of the loop points to the storage space of $arr2[2];

  • In the second foreach, we adopted the value transfer method. The first loop assigned a to $v, that is, a was assigned to $arr2[2], The same as above for the second time, the value of $arr2[2] becomes the value of $arr2[1], then $arr2 becomes [a,s,s], so it is the last one in the array The element becomes the value of the penultimate element

Solution:

  • Add unset($v); after the end of the first

    foreach
  • The second foreach loop does not use $vChange the variable with another name

Reference:

  • The problem of using foreach to change the value of an array in php

  • php array class object value passing reference passing difference

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template