foreach loop and reference of &$value

后端 未结 6 461
难免孤独
难免孤独 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条回答
  •  星月不相逢
    2020-12-05 04:01

    As phil stated in the comments:

    As mentioned in the manual, you should unset() references after use.


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

    Will return:

    Array
    (
        [0] => 2
        [1] => 3
        [2] => 4
        [3] => 5
    )
    

    Example


    Explanation

    Taken from the foreach() manual. (See the big red box)

    Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

    It basically means: That the referenced value &$value and the last element/item in the array, which in this case is 4 remain the same. To counter-act this issue, you'll have to unset() the value after use, otherwise it will stay in the array as its original value (if that makes sense).

    You should also read this: How does PHP 'foreach' actually work?

提交回复
热议问题