search

Home  >  Q&A  >  body text

Questions about php foreach reference

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?

typechotypecho2784 days ago875

reply all(3)I'll reply

  • 迷茫

    迷茫2017-07-04 13:47:55

    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

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-07-04 13:47:55

    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)

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-07-04 13:47:55

    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

    reply
    0
  • Cancelreply