skip to Main Content

Reproduced here: https://3v4l.org/DD33t#v7.4.33

Basically, I have an array containing arrays as elements. I’m looping through and adding an element to each of the sub-arrays by using `&` to reference the actual element instead of a copy used in the for loop.

$array = [
    ["foo" => 1], 
    ["bar" => 2]
];

foreach($array as &$element) {
    $element['test'] = true;
}

var_dump($array);

And the output:

array(2) {
  [0]=>
  array(2) {
    ["foo"]=>
    int(1)
    ["test"]=>
    bool(true)
  }
  [1]=>
  &array(2) {
    ["bar"]=>
    int(2)
    ["test"]=>
    bool(true)
  }
}

In the output, there is a & before the last element in the array, so my question is why does this behavior happen? Why does the last element become a pointer to the array instead of the array itself? How does using the for loop cause this kind of change to my array?

2

Answers


  1. In my opinion, the last element of the array is a reference because the reference persists after the loop has finished. So, the reference to the last element is still there even after the loop has completed. That is why when you dump the array using var_dump(), you can see that the last element is still a reference.

    Login or Signup to reply.
  2. Because PHP variables has scope of function. Your loop does not have its own scope and last processed element stays in memory, and no one unsets it.

    So yes, last element stays as pointer just because you use it by reference. Same effect can be seen here:

    $a = ['a', 'b'];
    
    foreach ($a as $element) {
    }
    
    echo $element; // b
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search