6

Possible Duplicate:
Reference - What does this symbol mean in PHP?

hi i have trouble to understand some of the & operator usage. i have come across with multiple examples and point out only those whitch i dont know what they really do ...

what does it mean when i'm:

1) using & in function name

function &foo() {}

2) using & in function parameter

function foo($id, &$desc) {}

3) usgin & in loop

foreach ($data as $key => &$item) {}
Community
  • 1
  • 1
nabizan
  • 3,185
  • 5
  • 26
  • 38

3 Answers3

6
function &foo() {}

Returns a variable by reference from calling foo().

function foo($id, &$desc) {}

Takes a value as the first parameter $id and a reference as the second parameter $desc. If $desc is modified within the function, the variable as passed by the calling code also gets modified.

The first two questions are answered by me in greater detail with clearer examples here.

And this:

foreach ($data as $key => &$item) {}

Uses foreach to modify an array's values by reference. The reference points to the values within the array, so when you change them, you change the array as well. If you don't need to know about the key within your loop, you can also leave out $key =>.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • When using `foreach` with a reference never forget that the reference keeps pointing to the last element after the loop. Always `unset()` it to prevent problems (e.g. assigning to a var with the same name later, causing the last array element to be modified). – ThiefMaster May 03 '11 at 09:39
2

The PHP manual has a huge section on references (the & operator) explaining what they are and how to use them.

In your particular examples:

1) Is a return by reference. You need to use the & when calling the function and when declaring it, like you have above: Return by Reference

2) Is passing a parameter by reference. You only need to use the & in the function definition, not when calling the function: Passing by Reference

3) Is using a reference in a foreach loop. This allows you to modify the $item value within the originating array when you're inside the loop.

All the complete information on PHP references is available in the manual.

Jamie Hurst
  • 331
  • 1
  • 3
0

The PHP documentation on references will answer all of those questions.

GWW
  • 43,129
  • 11
  • 115
  • 108