3

It's difficult to explain in word what I'm trying to do, so I'm providing a minimal example, see comments:

$g = array( 
    'a' => array(1, 2, 3), 
    'b' => array(4, 5, 6)
); // A global array

function &search($key) {
    global $g;
    return $g[$key];
}

$a = search('b'); // Now $a should be a reference to $g['b'], right?

$a[2] = 666;
print_r($a); // Ok changed
print_r($g); // Why not changed?

Tested on PHP 5.6.4.

Reason for what I'm trying to do is the fact the search function is obviously more complex in my use case (not just a key indexing!), and after the result has been found, it's handy to work on results: the original array is nested at various levels.

2
  • 1
    Because you're returning by value, not by reference; so modifying the returned value doesn't modify the global value Commented Jun 20, 2016 at 13:36
  • @MarkBaker Why you say I'm returning by value? Shouldn't &search return by reference? Commented Jun 20, 2016 at 13:37

1 Answer 1

4

From the manual:

Note: Unlike parameter passing, here you have to use & in both places - to indicate that you want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done for $myValue.

Your code just needs an extra ampersand (the reference "binding" one referred to above), as follows:

$a =& search('b');
Sign up to request clarification or add additional context in comments.

2 Comments

Greeeeeat! Thank you! I tough it was sufficient to use & just in the function declaration!
I have given up on this, when it comes to php. I could never get references, this way. For example, why is the purpose then of doing function &search($key){} ? What does that ampersand do in this case?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.