1

i thought, that i understand what references do. but now i meet an example, which can't understand anyway.

i saw an interesting script here, but why he use & in this script i can't understand. here is the part of script

foreach ($nodeList as $nodeId => &$node) 
{
    if (!$node['id_parrent'] || !array_key_exists($node['id_parrent'], $nodeList)) 
    {
        $tree[] = &$node;
    } 
    else 
    {
        $nodeList[$node['id_parrent']]['children'][] =&$node;
    }
}

if he doesn't make any changes on $node, why it is needed to use references here? there is nothing like $node = any changes, so why use =& $node, instead $node?

maybe you will help me to understand?

Thanks

Community
  • 1
  • 1
Simon
  • 22,637
  • 36
  • 92
  • 121
  • understanded. thanks much (p.s it is very useful thing, references:) – Simon Jun 27 '10 at 13:58
  • This is something they teach you in `C` language courses. You're asked to create a link-list using C arrays; this is the same except instead of storing references to prev/next you store references of children. – Salman A Aug 18 '12 at 09:19

3 Answers3

2

$tree[] = &$node;

When you do it like this, the tree array will store references to the same nodes as in the node list. If you change a node from the node list, it will be changed in the tree too and vice-versa of course. The same applies to the children array.

Without using references, the tree and children array would simply contain a copy of the node.

svens
  • 11,438
  • 6
  • 36
  • 55
1

if he doesn't make any changes on $node, why it is needed to use references here? there is nothing like $node = any changes, so why use =& $node, instead $node?

Because using a reference also saves you from copying the variable, thus saving memory and (in a usually negligeable dimension) performance.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • Actually that is not the case anymore with objects, as of PHP 5. In fact the entire call-time pass-by-reference construct is deprecated in PHP 5.3 anyway. – user268396 Jun 27 '10 at 14:10
1

I would suggest you to have a look at:

PHP: Pass by reference vs. Pass by value

This easily demonstrates why you need to pass variables by reference (&).

Example code taken:

function pass_by_value($param) {
  push_array($param, 4, 5);
}

$ar = array(1,2,3);

pass_by_value($ar);

foreach ($ar as $elem) {
  print "<br>$elem";
}

The code above prints 1, 2, 3. This is because the array is passed as value.

function pass_by_reference(&$param) {
  push_array($param, 4, 5);
}

$ar = array(1,2,3);

pass_by_reference($ar);

foreach ($ar as $elem) {
  print "<br>$elem";
}

The code above prints 1, 2, 3, 4, 5. This is because the array is passed as reference, meaning that the function (pass_by_reference) doesn't manipulate a copy of the variable passed, but the actual variable itself.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578