Why does PHP overwrite values when I iterate through this array twice (by reference, by value)

前端 未结 3 375
灰色年华
灰色年华 2020-12-11 06:47

If I iterate through an array twice, once by reference and then by value, PHP will overwrite the last value in the array if I use the same variable name for each loop. This

3条回答
  •  暖寄归人
    2020-12-11 07:09

    After the first loop $element is still a reference to the last element/value of $array.
    You can see that when you use var_dump() instead of print_r()

    array(5) {
      [0]=>
      int(2)
    ...
      [4]=>
      &int(2)
    }
    

    Note that & in &int(2).
    With the second loop you assign values to $element. And since it's still a reference the value in the array is changed, too. Try it with

    foreach($array as $element)
    {
      var_dump($array);
    }
    

    as the second loop and you'll see.
    So it's more or less the same as

    $array = range(1,5);
    $element = &$array[4];
    $element = $array[3];
    // and $element = $array[4];
    echo $array[4];
    

    (only with loops and multiplication ...hey, I said "more or less" ;-))

提交回复
热议问题