tags:

views:

284

answers:

5
+2  Q: 

PHP "&" operator

Hi,

I'm not a PHP programmer (but know other languages) and I'm trying to understand a web page that was done in PHP (5.1.6) in order to do some changes.

The page has the following code (simplified):

$db_hosts = array();
$sql = 'SELECT h.hostid, h.host FROM hosts h ';

$db_items = DBselect($sql);

while($db_item = DBfetch($db_items)){
   $name = $db_item['host'];
   $db_host = &$db_hosts[$db_item['hostid']];
}

What I'm trying to understand the last line $db_host = &$db_hosts[$db_item['hostid']];

It seems to be creating a new variable $db_host and putting something inside it, but don't understand &$db_hosts.

I'm in doubt because as far as I know, $db_hosts is an empty array.

I found this and this, but I'm not quite sure, because in this links, the operator is "=&", and in the code, the operator is attached to the variable "= &$db_hosts" (it has an space between = and &).

Since I tried to modify it and didn't got success, I thought that was better to ask for help...

TIA,

Bob

A: 

The & is used to get a reference to a variable. It's similar to references in other languages like C++, with some significant differences. See the PHP Manual's section on references.

Josh
Your thinking of the @ symbol.
Rook
@Michael Brooks: yes I was, sorry, I answered too quickly. I have corrected my answer.
Josh
+8  A: 

Those are references, they are similar to "pointers" in C or C++.

More info in the PHP manual.

In this case, since $db_hosts is empty, the construct $db_hosts[$db_item['hostid']] will create a new array with an empty item on the index of $db_item['hostid'] and return the item's reference, making $db_host act as an 'alias' for whatever $db_hosts[$db_item['hostid']] is currently.

LiraNuna
This is correct. I was doing too many things at once and replied too quickly :-)
Josh
And, as we are discussing PHP references, a link to the post entitled "Do not use PHP references" is in order - http://schlueters.de/blog/archives/125-Do-not-use-PHP-references.html
Tom Morris
+1  A: 

& is used as a reference, see what references are: http://php.net/manual/en/language.references.php

References in PHP are a means to access the same variable content by different names. They are not like C pointers; for instance, you cannot perform pointer arithmetic using them, they are not actual memory addresses, and so on.

dusoft
+2  A: 

Assigning that variable as a reference makes it so that if later on $db_host is changed, the corresponding entry in the $db_hosts array will change as well, and vice versa.

I've seen a fair bit of rather pointless use of references in PHP, cargo cult style. Perhaps this one is needed, perhaps not - you'd have to look at the rest of the program.

Alex JL