Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ampersand prepended at end of array var_dump

I wrote a piece of tutorial code and ran into something quite strange after running it.

My Chrome extension Var Dumpling didn't see the last entry in the array because an ampersand had been appended to the type of the value.

I tested with this piece of code:

$alphabet = array('a', 'b', 'c');

foreach ($alphabet as &$letter) {
  $letter .= 'a';
}

var_dump($alphabet);

The result of the var_dump is:

array(3) {
  [0]=>
  string(2) "aa"
  [1]=>
  string(2) "ba"
  [2]=>
  &string(2) "ca"
}

You can see that the last entry is &string(2) "ca" instead of what I would expect string(2) "ca". There is no problem in the logic part of this, I can call $alphabet[2] and it would return the value of the last entry ca.

What I am wondering is, is this convention or some weird hickup in PHP?

like image 340
Pepijn Avatar asked Oct 21 '14 11:10

Pepijn


1 Answers

This denotes a variable as being a Reference and is perfectly valid. In most cases, just ignore it and continue.

In this special case, it probably means that the last element of your array is still being referenced from your foreach loop. Since you used it as a Reference there and the last item from the loop still exists after the loop closed, the reference on that item is still there. Or in short:

After your loop, $letter still is a reference to $alphabet[2]. If you unset($letter), that ampersand should vanish.

http://php.net/manual/en/language.references.php

like image 62
ToBe Avatar answered Sep 27 '22 15:09

ToBe