Search code examples
phpforeachvar-dump

var_dump output using foreach reference loop


I am using a foreach loop with referencing, ie: foreach($elements as &$item)

Now when I use var_dump($elements); after the foreach(), the last element always has an & character prepended to it's variable-type (&string, &array, &boolean, etc).

Example output:

array(4) {
  [0]=>
  string(4) "this"
  [1]=>
  string(2) "is"
  [2]=>
  string(2) "an"
  [3]=>
  &string(7) "example"
}

Why is this and what functionality / impact does it have?


Solution

  • It is the address pointer. You can unset($item) to avoid this.

    Answers for your question:

    1. Why is this :

    You can find the reference in the manual

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

    This arises when you use reference in your foreach loop. The reference resides with the last array element.

    2. What functionality / impact does it have

    Consider this situation:

    <?php
    $arr = array(1, 2, 3, 4);
    foreach ($arr as &$value) {
    }
    
    print_r($arr);
    
    foreach ($arr as $value) {
    }
    
    print_r($arr);
    

    Your output will be:

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

    If you use unset:

    <?php
    $arr = array(1, 2, 3, 4);
    foreach ($arr as &$value) {
    }
    
    print_r($arr);
    unset($value);  <---
    
    foreach ($arr as $value) {
    }
    
    print_r($arr);
    

    Result will be:

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