foreach loop and reference of &$value

后端 未结 6 462
难免孤独
难免孤独 2020-12-05 03:26

Why is an empty foreach loop can change the result.

I have the following code:

$variable = [1,2,3,4];
foreach ($variable  as $key => &$value)          


        
6条回答
  •  猫巷女王i
    2020-12-05 03:38

    After loop you should unset this reference using:

    unset($value);
    

    So your whole code should work like this:

      $variable  = [1,2,3,4];
      foreach ($variable  as $key => &$value) {
        $value++;
      }
      unset($value);
      var_dump($variable); 
    

    There is no point to put unset($value); inside the loop

    Explanation - after loop $value is still set to the last element of array so you can use after your loop $value = 10; (before unset) and you will see that last element of array has been changed to 10. It seems that var_dump want to help us a bit in this case and shows there is reference for last element and of course when we use unset we have desired output of var_dump.

    You could also look at the following script:

    
    

    We don't use loop here and if reference is set to element of array, var_dump shows us this putting & before type of this element.

    However if the above code we changed reference and set it this way $x = &$array; var_dump wouldn't show us any reference.

    Also in the following code:

    
    

    var_dump() won't give us any hint.

提交回复
热议问题